feat: add request logging middleware
This commit is contained in:
		| @@ -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) { | ||||
|   | ||||
		Reference in New Issue
	
	Block a user
	 Grail Finder (aider)
					Grail Finder (aider)