Logging HTTP Responses Enhancements
Logging HTTP requests is a crucial aspect of debugging and performance monitoring. While there are solutions like Gorilla's LoggingHandler for logging requests, logging responses is often an overlooked task.
To address this, let's explore a modified version of Eric Broda's accepted answer that both logs responses and forwards them to the client:
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)) // Forward the response to the client for k, v := range rec.HeaderMap { w.Header()[k] = v } w.WriteHeader(rec.Code) rec.Body.WriteTo(w) } }
This modified function achieves the following:
By integrating this modified function into your application, you can seamlessly log both requests and responses, providing a comprehensive view of your HTTP communication.
The above is the detailed content of How Can I Effectively Log Both HTTP Requests and Responses in Go?. For more information, please follow other related articles on the PHP Chinese website!