diff --git a/handlers/middleware.go b/handlers/middleware.go index e006f80..b655f51 100644 --- a/handlers/middleware.go +++ b/handlers/middleware.go @@ -9,6 +9,7 @@ import ( "golias/config" "golias/pkg/cache" "net/http" + "time" ) var ( @@ -16,7 +17,37 @@ var ( memcache cache.Cache ) -// add middleware to log http requests; ai! +// responseWriterWrapper wraps http.ResponseWriter to capture status code +type responseWriterWrapper struct { + http.ResponseWriter + status int +} + +func (w *responseWriterWrapper) WriteHeader(status int) { + w.status = status + w.ResponseWriter.WriteHeader(status) +} + +// LogRequests logs all HTTP requests with method, path and duration +func LogRequests(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + log.Info("request started", "method", r.Method, "path", r.URL.Path) + + // Wrap response writer to capture status code + ww := &responseWriterWrapper{ResponseWriter: w} + + next.ServeHTTP(ww, r) + + duration := time.Since(start) + log.Debug("request completed", + "method", r.Method, + "path", r.URL.Path, + "status", ww.status, + "duration", duration.String(), + ) + }) +} func GetSession(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {