Home >Backend Development >Golang >How Can I Log HTTP Responses in a Go Web Application Using Gorilla Mux and Handlers?

How Can I Log HTTP Responses in a Go Web Application Using Gorilla Mux and Handlers?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-07 22:56:12735browse

How Can I Log HTTP Responses in a Go Web Application Using Gorilla Mux and Handlers?

Logging HTTP Responses with Go and Gorilla's Mux and Handler Packages

In a Go application, utilizing Gorilla's mux and handler packages for constructing a web application presents a challenge when trying to log HTTP responses. While logging requests is easily achieved with Gorilla's LoggingHandler, logging responses requires a different approach.

One potential solution is to create a custom middleware function that wraps the original handler. This middleware can intercept both the request and the response, allowing for logging of both as shown in the following code:

func logResponse(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Capture the request
        requestBytes, err := httputil.DumpRequest(r, true)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
        log.Printf("%q", requestBytes)

        // Create a new ResponseRecorder to capture the response
        rec := httptest.NewRecorder()
        next.ServeHTTP(rec, r)

        // Capture the response
        responseBytes := rec.Body.Bytes()
        log.Printf("%q", responseBytes)

        // Copy the recorder's headers and body into the original ResponseWriter
        for k, v := range rec.HeaderMap {
            w.Header()[k] = v
        }
        w.WriteHeader(rec.Code)
        w.Write(responseBytes)
    })
}

This middleware can then be utilized by wrapping the original handler in Gorilla's router:

// Import Gorilla packages
import (
    "github.com/gorilla/mux"
    "github.com/gorilla/handlers"
)

func main() {
    // Setup Gorilla router
    r := mux.NewRouter()

    // Wrap the handler with the logging middleware
    wrappedHandler := handlers.LoggingHandler(os.Stdout, http.HandlerFunc(handler))

    // Register the handler with the router
    r.Handle("/api/v1/users", wrappedHandler)

    // Start the server
    http.ListenAndServe(":8080", r)
}

By using this custom middleware, both the HTTP requests and responses can be easily logged, enhancing the observability of the application and aiding in debugging and performance monitoring.

The above is the detailed content of How Can I Log HTTP Responses in a Go Web Application Using Gorilla Mux and Handlers?. 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