package middleware import ( "log/slog" "net/http" "time" ) // responseWriter 捕获状态码,实现 http.ResponseWriter。 type responseWriter struct { http.ResponseWriter status int } func (rw *responseWriter) WriteHeader(code int) { rw.status = code rw.ResponseWriter.WriteHeader(code) } // Audit 记录每个 HTTP 请求的结构化审计日志。 func Audit(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() rw := &responseWriter{ResponseWriter: w, status: 200} next.ServeHTTP(rw, r) subject := "anonymous" if sub, ok := r.Context().Value(KeySubject).(string); ok { subject = sub } slog.Info("request", "method", r.Method, "path", r.URL.Path, "status", rw.status, "duration_ms", time.Since(start).Milliseconds(), "subject", subject, "remote_addr", r.RemoteAddr, ) }) }