middleware.go111 lines, 3.0 KB
| 1 | // Package httpx is the HTTP plumbing every service shares: middleware, JSON |
| 2 | // helpers, and one consistent way to turn errors into responses. |
| 3 | package httpx |
| 4 | |
| 5 | import ( |
| 6 | "log/slog" |
| 7 | "net/http" |
| 8 | "runtime/debug" |
| 9 | "slices" |
| 10 | "time" |
| 11 | ) |
| 12 | |
| 13 | // Middleware wraps a handler to add behavior around every request. |
| 14 | type Middleware func(http.Handler) http.Handler |
| 15 | |
| 16 | // Chain wraps h in mw. The first middleware is the outermost: it sees the |
| 17 | // request first, and the response last. |
| 18 | func Chain(h http.Handler, mw ...Middleware) http.Handler { |
| 19 | for _, m := range slices.Backward(mw) { |
| 20 | h = m(h) |
| 21 | } |
| 22 | return h |
| 23 | } |
| 24 | |
| 25 | // statusRecorder is a ResponseWriter that remembers the status code and counts |
| 26 | // the bytes written, which the standard ResponseWriter doesn't expose. |
| 27 | type statusRecorder struct { |
| 28 | http.ResponseWriter |
| 29 | status int |
| 30 | bytes int |
| 31 | } |
| 32 | |
| 33 | func (w *statusRecorder) WriteHeader(status int) { |
| 34 | if w.status == 0 { |
| 35 | w.status = status |
| 36 | } |
| 37 | w.ResponseWriter.WriteHeader(status) |
| 38 | } |
| 39 | |
| 40 | func (w *statusRecorder) Write(b []byte) (int, error) { |
| 41 | if w.status == 0 { |
| 42 | w.status = http.StatusOK // Write without WriteHeader means 200 |
| 43 | } |
| 44 | n, err := w.ResponseWriter.Write(b) |
| 45 | w.bytes += n |
| 46 | return n, err |
| 47 | } |
| 48 | |
| 49 | // Unwrap lets http.ResponseController reach the real ResponseWriter, for |
| 50 | // features like Flush that our wrapper doesn't implement itself. |
| 51 | func (w *statusRecorder) Unwrap() http.ResponseWriter { |
| 52 | return w.ResponseWriter |
| 53 | } |
| 54 | |
| 55 | // AccessLog logs one line per request when it completes: the method, path, |
| 56 | // status, duration and response size. Server errors are logged as errors. |
| 57 | func AccessLog(logger *slog.Logger) Middleware { |
| 58 | return func(next http.Handler) http.Handler { |
| 59 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 60 | if quiet(r) { |
| 61 | next.ServeHTTP(w, r) |
| 62 | return |
| 63 | } |
| 64 | start := time.Now() |
| 65 | rec := &statusRecorder{ResponseWriter: w} |
| 66 | next.ServeHTTP(rec, r) |
| 67 | |
| 68 | if rec.status == 0 { |
| 69 | rec.status = http.StatusOK // the handler wrote nothing at all |
| 70 | } |
| 71 | level := slog.LevelInfo |
| 72 | if rec.status >= 500 { |
| 73 | level = slog.LevelError |
| 74 | } |
| 75 | logger.LogAttrs(r.Context(), level, "request", |
| 76 | slog.String("method", r.Method), |
| 77 | slog.String("path", r.URL.Path), |
| 78 | slog.Int("status", rec.status), |
| 79 | slog.Duration("duration", time.Since(start)), |
| 80 | slog.Int("bytes", rec.bytes), |
| 81 | ) |
| 82 | }) |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | // Recover turns a panic in a handler into a 500 JSON error, and logs it with |
| 87 | // its stack trace. |
| 88 | func Recover(logger *slog.Logger) Middleware { |
| 89 | return func(next http.Handler) http.Handler { |
| 90 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 91 | defer func() { |
| 92 | v := recover() |
| 93 | if v == nil { |
| 94 | return |
| 95 | } |
| 96 | if v == http.ErrAbortHandler { |
| 97 | panic(v) // a deliberate abort: let net/http handle it |
| 98 | } |
| 99 | logger.ErrorContext(r.Context(), "panic recovered", |
| 100 | "panic", v, |
| 101 | "stack", string(debug.Stack()), |
| 102 | ) |
| 103 | writeError(w, r, http.StatusInternalServerError, errorDetail{ |
| 104 | Code: "internal", |
| 105 | Message: "internal server error", |
| 106 | }) |
| 107 | }() |
| 108 | next.ServeHTTP(w, r) |
| 109 | }) |
| 110 | } |
| 111 | } |