forked from mtusi2026/mtusi2026lab4
45 lines
1003 B
Go
45 lines
1003 B
Go
package middleware
|
|
|
|
import (
|
|
"log"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
// responseWriterInterceptor перехватывает статус-код ответа для логов
|
|
type responseWriterInterceptor struct {
|
|
http.ResponseWriter
|
|
statusCode int
|
|
}
|
|
|
|
func (w *responseWriterInterceptor) WriteHeader(code int) {
|
|
w.statusCode = code
|
|
w.ResponseWriter.WriteHeader(code)
|
|
}
|
|
|
|
func Logger(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
start := time.Now()
|
|
|
|
interceptor := &responseWriterInterceptor{
|
|
ResponseWriter: w,
|
|
statusCode: http.StatusOK, // дефолтный статус если WriteHeader не вызывался
|
|
}
|
|
|
|
next.ServeHTTP(interceptor, r)
|
|
|
|
reqID := GetRequestID(r.Context())
|
|
duration := time.Since(start)
|
|
|
|
// метаданные без r.Body
|
|
log.Printf(
|
|
"[HTTP] %s %s | status: %d | duration: %v | request_id: %s",
|
|
r.Method,
|
|
r.URL.Path,
|
|
interceptor.statusCode,
|
|
duration,
|
|
reqID,
|
|
)
|
|
})
|
|
}
|