Home >Backend Development >Golang >How Can I Efficiently Log Both HTTP Requests and Responses in Go?

How Can I Efficiently Log Both HTTP Requests and Responses in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-12-04 00:09:10709browse

How Can I Efficiently Log Both HTTP Requests and Responses in Go?

Logging Both Requests and Responses in Go

When creating a complex application in Go, handling HTTP requests and responses efficiently is crucial. While the Gorilla web toolkit's mux and handler packages simplify request handling, logging responses remains a challenge.

To address this, the accepted answer by Eric Broda offers a solution that captures request details. However, it fails to log the actual response sent to the client. To resolve this, a modification to the code is necessary:

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)
    }
}

This modified code intercepts the response and copies it to the response writer, enabling logging of both requests and responses.

The above is the detailed content of How Can I Efficiently Log Both HTTP Requests and Responses in Go?. 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