37 lines
699 B
Go
37 lines
699 B
Go
package middleware
|
|
|
|
import (
|
|
"log/slog"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
type WrappedWriter struct {
|
|
http.ResponseWriter
|
|
StatusCode int
|
|
}
|
|
|
|
func (w *WrappedWriter) WriteHeader(code int) {
|
|
w.StatusCode = code
|
|
w.ResponseWriter.WriteHeader(code)
|
|
}
|
|
|
|
func Log(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
start := time.Now()
|
|
|
|
wrapped := &WrappedWriter{
|
|
ResponseWriter: w,
|
|
StatusCode: http.StatusOK,
|
|
}
|
|
next.ServeHTTP(wrapped, r)
|
|
|
|
slog.InfoContext(r.Context(), "request",
|
|
"remoteAddr", r.RemoteAddr,
|
|
"status", wrapped.StatusCode,
|
|
"method", r.Method,
|
|
"path", r.URL.Path,
|
|
"duration", time.Since(start).String())
|
|
})
|
|
}
|