This article discusses an alternative approach to obtaining the HTTP response for logging purposes without resorting to faking requests or modifying http.ResponseWriter. We introduce the concept of middleware chaining, providing a functional style implementation.
Middleware chaining involves passing control to a chain of handlers that perform specific tasks before and after the main request execution. These handlers, known as middleware, receive the request and the next handler in the chain, ensuring ordered execution.
We define a custom middleware function that acts as an HTTP handler combinator:
<code class="go">func NewResponseLoggingHandler(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // Replace the response writer with a recorder for subsequent handlers c := httptest.NewRecorder() next(c, r) // Copy data from the recorder to the original response writer for k, v := range c.HeaderMap { w.Header()[k] = v } w.WriteHeader(c.Code) c.Body.WriteTo(w) } }</code>
To ensure automatic response logging for all handlers in a specific category, we create another handler combinator that encapsulates the logging middleware:
<code class="go">func NewDefaultHandler(next http.HandlerFunc) http.HandlerFunc { return NewResponseLoggingHandler(NewOtherStuffHandler(next)) }</code>
Now, any handler chain instantiated using NewDefaultHandler will automatically include response logging and other default behaviors.
<code class="go">h := NewDefaultHandler(...)</code>
Using middleware chaining, we can transparently intercept and log HTTP responses without the need for request faking or modifying the http.ResponseWriter. This approach allows for modular logging and simplifies handler management.
The above is the detailed content of How to Log HTTP Responses Without Modifying http.ResponseWriter?. For more information, please follow other related articles on the PHP Chinese website!