dongmi5607 2016-07-21 10:10
浏览 40
已采纳

如何在杜松子酒中记录响应正文

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:

func Logger() gin.HandlerFunc {

    return func(c *gin.Context) {

        c.Next()

        statusCode := c.Writer.Status()
        if statusCode >= 400 {
            //ok this is an request with error, let's make a record for it
            //log body here
        }
    }
}

My question is, how to get response body from Context in middleware?

  • 写回答

2条回答 默认 最新

  • dongliuxia9495 2016-07-24 03:48
    关注

    You need to intercept writing of response and store it somewhere first. Then you can log it. And to do that you need to implement your own Writer intercepting 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 {
            //ok this is an request with error, let's make a record for it
            // now print body (or log in your preferred way)
            fmt.Println("Response body: " + blw.body.String())
        }
    }
    

    Then use this middleware like this:

    router.Use(ginBodyLogMiddleware)
    

    Note that this sill won't work for static files as gin does not seem to use c.Writer for them. But in most cases, that's what you want anyway.

    If you want to intercept all files, you need to use a slightly more complicated approach. Instead of Middleware, you'll need to implement a wrapper http.Handler that will wrap gin.Engine and will use same approach as shown above to intercept and log whatever is written to http.ResponseWriter. Then run gin server like this:

    ginRouter := gin.New()
    // configure your middleware and routes as required
    
    // Run http server as follows, where bodyLogHandler is your wrapper handler
    http.ListenAndServe(bindAddress, &bodyLogHandler{wrappedHandler: ginRouter}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行