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:
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)
}
}
To ensure automatic response logging for all handlers in a specific category, we create another handler combinator that encapsulates the logging middleware:
func NewDefaultHandler(next http.HandlerFunc) http.HandlerFunc {
return NewResponseLoggingHandler(NewOtherStuffHandler(next))
}
Now, any handler chain instantiated using NewDefaultHandler will automatically include response logging and other default behaviors.
h := NewDefaultHandler(...)
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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3