Home > Backend Development > Golang > 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
Release: 2024-10-27 10:29:03
Original
324 people have browsed it

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>
Copy after login

These combinators can then be chained to form a handler:

<code class="go">h := NewFooHandler(NewBarHandler(NewBazHandler(Sink)))</code>
Copy after login

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>
Copy after login

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>
Copy after login

By using this default handler:

<code class="go">h := NewDefaultHandler(...)</code>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template