forked from mtusi2026/mtusi2026lab6
35 lines
792 B
Go
35 lines
792 B
Go
package middleware
|
|
|
|
import (
|
|
"log/slog"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/go-chi/chi/v5/middleware"
|
|
|
|
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/headers"
|
|
)
|
|
|
|
func LoggingMiddleware() Middleware {
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
started := time.Now()
|
|
wrapped := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
|
|
next.ServeHTTP(wrapped, r)
|
|
|
|
status := wrapped.Status()
|
|
if status == 0 {
|
|
status = http.StatusOK
|
|
}
|
|
slog.InfoContext(r.Context(), "http request",
|
|
"method", r.Method,
|
|
"path", r.URL.Path,
|
|
"status", status,
|
|
"duration", time.Since(started),
|
|
"bytes", wrapped.BytesWritten(),
|
|
"request_id", w.Header().Get(headers.HeaderRequestID),
|
|
)
|
|
})
|
|
}
|
|
}
|