When using the Gin framework, you need to get the response flow in the middleware without affecting the output, so use a trick to get the content of the response flow without affecting the output.

Construct a response flow that can be copied automatically

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 the code

The above code inherits the response stream from GIN, adds the body property to record the copied content, and overwrites the Write() method to Write bytes to both the ResponseWriter and the copied stream.

use

Gin.Context.Writer needs to be replaced with the bodyLogWriter above, as shown below:

func(c *gin.Context) {
    blw := &bodyLogWriter{
	body: bytes.NewBufferString(""),
	ResponseWriter: c.Writer,
    }
    c.Writer = blw
    // Other code
}
Copy the code

provenance

Code from the Nuggets For building enterprise-level RESTful API services based on the Go language