gologgingreturn-codego-chi

How to log the HTTP return code with the chi router?


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?


Solution

  • 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())
            
        })
    }