Standalone net/http middleware for panic recovery, CORS, request ID injection, and request logging. What's included: - Recover(): panic -> 500, captures debug.Stack, no logger required - CORS(origins): OPTIONS 204 preflight, origin allowlist, package-wide method/header constants - RequestID(generator): injects ID via logz.WithRequestID, sets X-Request-ID response header - RequestLogger(logger): logs method/path/status/latency/request_id; Error for 5xx, Info otherwise - Logger interface: Info, Error, With — duck-typed; satisfied by logz.Logger - StatusRecorder: exported http.ResponseWriter wrapper that captures written status code - Direct logz import for context helpers (documented exception to ADR-001) Tested-via: todo-api POC integration Reviewed-against: docs/adr/
65 lines
1.8 KiB
Go
65 lines
1.8 KiB
Go
package httpmw
|
|
|
|
import (
|
|
"net/http"
|
|
"time"
|
|
|
|
"code.nochebuena.dev/go/logz"
|
|
)
|
|
|
|
// Logger is the minimal interface httpmw needs — satisfied by logz.Logger via duck typing.
|
|
// httpmw does NOT duck-type the Logger for context purposes (it imports logz for
|
|
// logz.WithRequestID / logz.GetRequestID context helpers).
|
|
type Logger interface {
|
|
Info(msg string, args ...any)
|
|
Error(msg string, err error, args ...any)
|
|
With(args ...any) Logger
|
|
}
|
|
|
|
// StatusRecorder wraps http.ResponseWriter to expose the written status code.
|
|
type StatusRecorder struct {
|
|
http.ResponseWriter
|
|
Status int
|
|
}
|
|
|
|
func (r *StatusRecorder) WriteHeader(code int) {
|
|
r.Status = code
|
|
r.ResponseWriter.WriteHeader(code)
|
|
}
|
|
|
|
// logzLogger is the subset we need from logz.Logger for RequestLogger.
|
|
// We accept the Logger interface (duck-typed) but need to also use logz.GetRequestID.
|
|
// Those two concerns are separate: Logger injection = duck-typed; context helpers = logz import.
|
|
|
|
// RequestLogger logs each request with method, path, status code, latency, and request ID.
|
|
func RequestLogger(logger Logger) func(http.Handler) http.Handler {
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
rec := &StatusRecorder{ResponseWriter: w, Status: http.StatusOK}
|
|
start := time.Now()
|
|
next.ServeHTTP(rec, r)
|
|
latency := time.Since(start)
|
|
|
|
reqID := logz.GetRequestID(r.Context())
|
|
if rec.Status >= 500 {
|
|
logger.Error("http: request",
|
|
nil,
|
|
"method", r.Method,
|
|
"path", r.URL.Path,
|
|
"status", rec.Status,
|
|
"latency", latency.String(),
|
|
"request_id", reqID,
|
|
)
|
|
} else {
|
|
logger.Info("http: request",
|
|
"method", r.Method,
|
|
"path", r.URL.Path,
|
|
"status", rec.Status,
|
|
"latency", latency.String(),
|
|
"request_id", reqID,
|
|
)
|
|
}
|
|
})
|
|
}
|
|
}
|