2

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?

WoJ
  • 27,165
  • 48
  • 180
  • 345
  • #1 To log something *after* the handler's done you can simply put the log statement below the `next.ServerHTTP(w, r)` call, instead of above. Or use a `defer` if you want to ensure that the log is made even in a case where the handler panics. – mkopriva Apr 01 '22 at 17:34
  • #2 To be able to get access to the status code however you'll need to wrap the `w` response writer into a custom implementation, one that records the status code and gives you access to it. For an example of how to do that, you can take a look at this answer to [this question](https://stackoverflow.com/questions/66528234/log-http-responsewriter-content). – mkopriva Apr 01 '22 at 17:34

1 Answers1

0

I think you need render from go-chi library.
https://github.com/go-chi/render/tree/v1.0.1

Example of usage is here:
https://github.com/go-chi/chi/blob/master/_examples/rest/main.go

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 02 '22 at 02:16