all repos

rss-tools @ d1f2b81248031b80c9c7e4fc9b3a1ddf318da7eb

get rss feed from sources that(i need and) dont provide one

rss-tools/app/http.go (view raw)

Oleksandr Smirnov Oleksandr Smirnov
olexsmir@gmail.com
init, 1 month ago
1
package app
2
3
import (
4
	"log/slog"
5
	"net/http"
6
	"time"
7
)
8
9
func (a *App) recoverMiddleware(next http.Handler) http.Handler {
10
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
11
		defer func() {
12
			if err := recover(); err != nil {
13
				a.Logger.Error("recover middleware", "err", err)
14
				w.WriteHeader(http.StatusInternalServerError)
15
			}
16
		}()
17
		next.ServeHTTP(w, r)
18
	})
19
}
20
21
func (a *App) loggingMiddleware(next http.Handler) http.Handler {
22
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
23
		start := time.Now()
24
		wrapped := wrapResponseWriter(w)
25
		next.ServeHTTP(wrapped, r)
26
		slog.Info("http request",
27
			"method", r.Method,
28
			"status", wrapped.status,
29
			"path", r.URL.Path,
30
			"latency", time.Since(start).String(),
31
			"ua", r.UserAgent(),
32
		)
33
	})
34
}
35
36
type responseWriter struct {
37
	http.ResponseWriter
38
	status      int
39
	wroteHeader bool
40
}
41
42
func wrapResponseWriter(w http.ResponseWriter) *responseWriter {
43
	return &responseWriter{ResponseWriter: w}
44
}
45
46
func (rw *responseWriter) Status() int {
47
	return rw.status
48
}
49
50
func (rw *responseWriter) WriteHeader(code int) {
51
	if rw.wroteHeader {
52
		return
53
	}
54
55
	rw.status = code
56
	rw.ResponseWriter.WriteHeader(code)
57
	rw.wroteHeader = true
58
}
59
60
func (rw *responseWriter) Flush() {
61
	if f, ok := rw.ResponseWriter.(http.Flusher); ok {
62
		f.Flush()
63
	}
64
}