feat: some refactoring
This commit is contained in:
42
internal/apiserver/middleware/logging.go
Normal file
42
internal/apiserver/middleware/logging.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"git.nwaifu.su/sergey/MyGoServer/internal/apiserver/logger"
|
||||
rhttp "git.nwaifu.su/sergey/MyGoServer/pkg/http"
|
||||
)
|
||||
|
||||
// LoggingMiddleware logs HTTP requests
|
||||
func LoggingMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
|
||||
// Use the custom response writer to capture status code
|
||||
rw := rhttp.NewResponseWriter(w)
|
||||
|
||||
next.ServeHTTP(rw, r)
|
||||
|
||||
// Log the request
|
||||
logger := logger.GetLogger()
|
||||
logger.WithFields(map[string]interface{}{
|
||||
"method": r.Method,
|
||||
"uri": r.RequestURI,
|
||||
"remote_addr": r.RemoteAddr,
|
||||
"user_agent": r.UserAgent(),
|
||||
"status_code": rw.GetStatusCode(),
|
||||
"duration": time.Since(start).String(),
|
||||
"request_id": getRequestID(r.Context()),
|
||||
}).Info("HTTP request")
|
||||
})
|
||||
}
|
||||
|
||||
// getRequestID retrieves request ID from context
|
||||
func getRequestID(ctx context.Context) string {
|
||||
if id, ok := ctx.Value("request_id").(string); ok {
|
||||
return id
|
||||
}
|
||||
return ""
|
||||
}
|
||||
Reference in New Issue
Block a user