How to log response body in gin

后端 未结 2 739
甜味超标
甜味超标 2021-02-04 11:04

I need to log the response body in a middleware of gin, but I don\'t find how to get the response body. Can anyone help?

I am using a middleware like this:



        
2条回答
  •  面向向阳花
    2021-02-04 11:21

    FYI

    Note: implement WriteString() if using c.String() for writing response body

    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 (w bodyLogWriter) WriteString(s string) (int, error) {
        w.body.WriteString(s)
        return w.ResponseWriter.WriteString(s)
    }
    
    func ginBodyLogMiddleware() gin.HandlerFunc {
        return func(c *gin.Context) {
            blw := &bodyLogWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer}
            c.Writer = blw
            c.Next()
    
            fmt.Println("Response body: " + blw.body.String())
        }
    }
    
    ...
    
    // register
    router := r.Group("/", ginBodyLogMiddleware())
    

提交回复
热议问题