How to Capture and Log Response Body in Gin Middleware?

Mary-Kate Olsen
Release: 2024-11-12 01:44:01
Original
224 people have browsed it

How to Capture and Log Response Body in Gin Middleware?

Logging Response Body in Gin Middleware

In middleware, you may need to capture and log the response body for debugging or auditing purposes. So, how can we access the response body from the middleware context in Gin?

Gin manages response writing internally, making it tricky to directly obtain the body. To overcome this, we need to implement our own Writer that intercepts the write operations. Here's a step-by-step approach:

  1. Create a Custom Writer:
type bodyLogWriter struct {
    gin.ResponseWriter
    body *bytes.Buffer
}

func (w bodyLogWriter) Write(b []byte) (int, error) {
    w.body.Write(b)
    return w.ResponseWriter.Write(b)
}
Copy after login

This writer buffers the response body alongside writing it to the original writer.

  1. Implement a Middleware:
func ginBodyLogMiddleware(c *gin.Context) {
    blw := &bodyLogWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer}
    c.Writer = blw
    c.Next()

     statusCode := c.Writer.Status()
    if statusCode >= 400 {
        fmt.Println("Response body: " + blw.body.String())
    }
}
Copy after login

In the middleware, we assign our custom writer blw to the context, ensuring that all responses will be captured by it. Then, we log the body if the status code is an error.

  1. Use the Middleware:
router.Use(ginBodyLogMiddleware)
Copy after login

Now, when requests are handled by your Gin router, the middleware will intercept and log the response bodies for requests with error status codes.

Note that this approach won't log response bodies for static files, but it should address the use case for most dynamic content. If you need to intercept all files, you'll require a more complex wrapper around the Gin engine.

The above is the detailed content of How to Capture and Log Response Body in Gin 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template