package middleware import ( "net/http" "tailly_back_v2/internal/service" "time" ) func AuditMiddleware(audit service.AuditService, action string) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() rw := &responseRecorder{w, http.StatusOK, 0} next.ServeHTTP(rw, r) duration := time.Since(start) status := "success" if rw.status >= 400 { status = "failed" } audit.LogEvent( r.Context(), action, "request", nil, r, status, map[string]interface{}{ "method": r.Method, "path": r.URL.Path, "status": rw.status, "duration": duration.String(), }, ) }) } } type responseRecorder struct { http.ResponseWriter status int size int } func (r *responseRecorder) WriteHeader(status int) { r.status = status r.ResponseWriter.WriteHeader(status) } func (r *responseRecorder) Write(b []byte) (int, error) { size, err := r.ResponseWriter.Write(b) r.size += size return size, err }