Home  >  Article  >  Backend Development  >  How to Log Real-Time HTTP Responses with `http.HandleFunc` and Middleware?

How to Log Real-Time HTTP Responses with `http.HandleFunc` and Middleware?

DDD
DDDOriginal
2024-10-27 10:29:03237browse

How to Log Real-Time HTTP Responses with `http.HandleFunc` and Middleware?

Logging Incoming HTTP Requests with http.HandleFunc

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.

Middleware Chaining

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>

Applying to HTTP.HandleFunc

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn