Home > Backend Development > Golang > How Can I Effectively Log HTTP Responses in Go?

How Can I Effectively Log HTTP Responses in Go?

Patricia Arquette
Release: 2024-11-28 11:08:11
Original
316 people have browsed it

How Can I Effectively Log HTTP Responses in Go?

Logging HTTP Responses Using Go

Logging requests in Go is straightforward with packages like Gorilla's mux and handler. However, logging responses can be trickier. This article explores how to accomplish this.

Using a Custom Logging Handler

One solution is to create a custom logging handler that wraps an HTTP handler function. Eric Broda's code below provides an initial framework:

func logHandler(fn http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        x, err := httputil.DumpRequest(r, true)
        if err != nil {
            http.Error(w, fmt.Sprint(err), http.StatusInternalServerError)
            return
        }
        log.Println(fmt.Sprintf("%q", x))
    }
}
Copy after login

Modifying the Response

To actually send the response to the client, a modification to the code is needed:

func logHandler(fn http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        x, err := httputil.DumpRequest(r, true)
        if err != nil {
            http.Error(w, fmt.Sprint(err), http.StatusInternalServerError)
            return
        }
        log.Println(fmt.Sprintf("%q", x))
        rec := httptest.NewRecorder()
        fn(rec, r)
        log.Println(fmt.Sprintf("%q", rec.Body))        

        // this copies the recorded response to the response writer
        for k, v := range rec.HeaderMap {
            w.Header()[k] = v
        }
        w.WriteHeader(rec.Code)
        rec.Body.WriteTo(w)
    }
}
Copy after login

This modified code wraps the handler function and logs both the request and the response body. By placing this logging handler in the middleware stack, you can easily log responses throughout your application.

The above is the detailed content of How Can I Effectively Log HTTP Responses in Go?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template