Logging HTTP Responses Using Go
Logging requests in Go is straightforward with packages like Gorilla's mux and handler. However, logging responses can be trickier. This article explores how to accomplish this.
Using a Custom Logging Handler
One solution is to create a custom logging handler that wraps an HTTP handler function. Eric Broda's code below provides an initial framework:
func logHandler(fn http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { x, err := httputil.DumpRequest(r, true) if err != nil { http.Error(w, fmt.Sprint(err), http.StatusInternalServerError) return } log.Println(fmt.Sprintf("%q", x)) } }
Modifying the Response
To actually send the response to the client, a modification to the code is needed:
func logHandler(fn http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { x, err := httputil.DumpRequest(r, true) if err != nil { http.Error(w, fmt.Sprint(err), http.StatusInternalServerError) return } log.Println(fmt.Sprintf("%q", x)) rec := httptest.NewRecorder() fn(rec, r) log.Println(fmt.Sprintf("%q", rec.Body)) // this copies the recorded response to the response writer for k, v := range rec.HeaderMap { w.Header()[k] = v } w.WriteHeader(rec.Code) rec.Body.WriteTo(w) } }
This modified code wraps the handler function and logs both the request and the response body. By placing this logging handler in the middleware stack, you can easily log responses throughout your application.
The above is the detailed content of How Can I Effectively Log HTTP Responses in Go?. For more information, please follow other related articles on the PHP Chinese website!