You need to intercept the response record and first save it somewhere. Then you can register it. And for this you need to implement your own Writer that intercepts Write () calls.
For example, as follows:
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)
}
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())
}
}
Then use this middleware as follows:
router.Use(ginBodyLogMiddleware)
, , , , c.Writer . , .
, . http.Handler, gin.Engine , , , http.ResponseWriter. gin :
ginRouter := gin.New()
http.ListenAndServe(bindAddress, &bodyLogHandler{wrappedHandler: ginRouter}