Home > Article > Backend Development > 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:
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.
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.
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!