duanou3868 2019-08-05 22:02
浏览 127
已采纳

如何从中间件记录响应主体?

I tried to log the response body from middleware. I can get all the data related to the Request object. Now try to log the response code and response body for a single request.

I was trying to catch the response body and response code from w http.ResponseWriter, but could not succeed. Here is the sample code. I am using go's default http and logrus for logging.

next.ServeHTTP(w, r.WithContext(ctx))
end := time.Now().UTC()
latency := end.Sub(start)
// request logging
log.WithFields(log.Fields{
    "path":      r.URL.Path,
    "method":    r.Method,
    "body":      body,
    "auth_user": claims,
    "latency":   latency,
    "useragent": r.Header.Get("User-Agent"),
    "response_body": ,// cannot get response body here
    "status": "", //cannot get response header here
}).Info("request data")

Can someone help me with that, please?

  • 写回答

1条回答 默认 最新

  • dongyonglie5132 2019-08-05 22:28
    关注

    To get response body and status code, you have to implement your own ResponseWriter. Here you can find full example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部