I use chi
as my router and wrote a simple middleware that logs the request being made:
func logCalls(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Info().Msgf("%v → %v", r.URL, r.RemoteAddr)
next.ServeHTTP(w, r)
})
}
It works great but I am missing the HTTP return code.
The HTTP return code will obviously be available once all the routes are exhausted but at the same time I have to use my middleware before the routes.
Is there a way to hook it after the routing is done, and therefore have the return code I can log?
NewWrapResponseWriter worked for me:
import "github.com/go-chi/chi/v5/middleware"
func logCalls(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
next.ServeHTTP(ww, r)
log.Info().Msgf("%v → %v %v", r.URL, r.RemoteAddr, ww.Status())
})
}