From 081bfdee0f36db671c80d355809aaab16dc64ea5 Mon Sep 17 00:00:00 2001 From: "Grail Finder (aider)" Date: Fri, 2 May 2025 10:21:16 +0300 Subject: [PATCH] feat: add request logging middleware --- handlers/middleware.go | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) 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) {