rss-tools/app/http.go (view raw)
| 1 | package app |
| 2 | |
| 3 | import ( |
| 4 | "net/http" |
| 5 | "strings" |
| 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 | a.Logger.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 | func (a *App) authMiddleware(next http.Handler) http.Handler { |
| 37 | expected := strings.TrimSpace(a.Config.AuthToken) |
| 38 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 39 | queryToken := strings.TrimSpace(r.URL.Query().Get("token")) |
| 40 | headerToken := strings.TrimSpace(r.Header.Get("Authorization")) |
| 41 | if queryToken == expected || headerToken == expected { |
| 42 | next.ServeHTTP(w, r) |
| 43 | return |
| 44 | } |
| 45 | |
| 46 | http.Error(w, "unauthorized", http.StatusUnauthorized) |
| 47 | }) |
| 48 | } |
| 49 | |
| 50 | type responseWriter struct { |
| 51 | http.ResponseWriter |
| 52 | status int |
| 53 | wroteHeader bool |
| 54 | } |
| 55 | |
| 56 | func wrapResponseWriter(w http.ResponseWriter) *responseWriter { |
| 57 | return &responseWriter{ResponseWriter: w} |
| 58 | } |
| 59 | |
| 60 | func (rw *responseWriter) Status() int { |
| 61 | return rw.status |
| 62 | } |
| 63 | |
| 64 | func (rw *responseWriter) WriteHeader(code int) { |
| 65 | if rw.wroteHeader { |
| 66 | return |
| 67 | } |
| 68 | |
| 69 | rw.status = code |
| 70 | rw.ResponseWriter.WriteHeader(code) |
| 71 | rw.wroteHeader = true |
| 72 | } |
| 73 | |
| 74 | func (rw *responseWriter) Flush() { |
| 75 | if f, ok := rw.ResponseWriter.(http.Flusher); ok { |
| 76 | f.Flush() |
| 77 | } |
| 78 | } |