Home >Backend Development >Golang >How Can I Effectively Log Both HTTP Requests and Responses in Go with Gorilla Mux?

How Can I Effectively Log Both HTTP Requests and Responses in Go with Gorilla Mux?

Susan Sarandon
Susan SarandonOriginal
2024-12-03 00:06:14322browse

How Can I Effectively Log Both HTTP Requests and Responses in Go with Gorilla Mux?

Logging HTTP Responses with Go and Gorilla

When building complex web applications with Go and the Gorilla web toolkit, logging both HTTP requests and responses is essential for debugging and analysis. While logging requests is straightforward using Gorilla's LoggingHandler, logging responses poses a challenge.

Logging Responses

The provided solution by Eric Broda effectively logs responses, but it doesn't send the response to the client. Here's a modified version that retains the functionality of the original code while ensuring the response reaches the client:

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

To utilize this function, simply wrap your handler function with logHandler:

http.HandleFunc("/", logHandler(myHandler))

This modification ensures that both requests and responses are logged while still correctly delivering the response to the client.

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