Home  >  Article  >  Backend Development  >  How to Capture and Log Response Body in Gin Middleware?

How to Capture and Log Response Body in Gin Middleware?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-12 01:44:01225browse

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

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

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)

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!

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