In our previous discussion, we explored inspecting HTTP responses using a fake request, a technique suitable for unit tests. However, we also seek a way to log real-time response data on a live server.
A prevalent approach involves creating a middleware chain. Libraries like Negroni offer middleware functionality, where handlers are combined and executed sequentially. A minimal middleware implementation can be achieved using handler combinators:
<code class="go">func NewFooHandler(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // Do pre-handling tasks next(w, r) // Do post-handling tasks } }</code>
These combinators can then be chained to form a handler:
<code class="go">h := NewFooHandler(NewBarHandler(NewBazHandler(Sink)))</code>
To apply this technique to your problem, you can create a handler combinator:
<code class="go">func NewResponseLoggingHandler(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // Record the response c := httptest.NewRecorder() next(c, r) // Copy responses for k, v := range c.HeaderMap { w.Header()[k] = v } w.WriteHeader(c.Code) c.Body.WriteTo(w) } }</code>
Now, you can create a default handler that combines custom handlers with response logging:
<code class="go">func NewDefaultHandler(next http.HandlerFunc) http.HandlerFunc { return NewResponseLoggingHandler(NewOtherStuffHandler(next)) }</code>
By using this default handler:
<code class="go">h := NewDefaultHandler(...)</code>
All subsequent handlers will automatically include response logging.
The above is the detailed content of How to Log Real-Time HTTP Responses with `http.HandleFunc` and Middleware?. For more information, please follow other related articles on the PHP Chinese website!