2022-10-30 02:15:35 +00:00
|
|
|
package mid
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
|
2023-03-21 04:32:10 +00:00
|
|
|
"github.com/go-chi/chi/v5/middleware"
|
2022-10-30 02:15:35 +00:00
|
|
|
"github.com/rs/zerolog"
|
|
|
|
)
|
|
|
|
|
2023-03-21 04:32:10 +00:00
|
|
|
type spy struct {
|
2022-10-30 02:15:35 +00:00
|
|
|
http.ResponseWriter
|
2023-03-21 04:32:10 +00:00
|
|
|
status int
|
2022-10-30 02:15:35 +00:00
|
|
|
}
|
|
|
|
|
2023-03-21 04:32:10 +00:00
|
|
|
func (s *spy) WriteHeader(status int) {
|
|
|
|
s.status = status
|
|
|
|
s.ResponseWriter.WriteHeader(status)
|
2022-10-30 02:15:35 +00:00
|
|
|
}
|
|
|
|
|
2023-03-21 04:32:10 +00:00
|
|
|
func Logger(l zerolog.Logger) func(http.Handler) http.Handler {
|
|
|
|
return func(h http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
reqID := r.Context().Value(middleware.RequestIDKey).(string)
|
2022-10-30 02:15:35 +00:00
|
|
|
|
2023-03-21 04:32:10 +00:00
|
|
|
l.Info().Str("method", r.Method).Str("path", r.URL.Path).Str("rid", reqID).Msg("request received")
|
2022-10-30 02:15:35 +00:00
|
|
|
|
2023-03-21 04:32:10 +00:00
|
|
|
s := &spy{ResponseWriter: w}
|
|
|
|
h.ServeHTTP(s, r)
|
2022-10-30 02:15:35 +00:00
|
|
|
|
2023-03-21 04:32:10 +00:00
|
|
|
l.Info().Str("method", r.Method).Str("path", r.URL.Path).Int("status", s.status).Str("rid", reqID).Msg("request finished")
|
2022-10-30 02:15:35 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|