gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:40:21 26 4
gpt4 key购买 nike

我尝试从中间件记录响应正文。我可以获得与Request对象有关的所有数据。现在尝试记录单个请求的响应代码和响应正文。

我试图从w http.ResponseWriter捕获响应正文和响应代码,但未能成功。这是示例代码。我正在使用go的默认httplogrus进行日志记录。

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")

有人可以帮我吗?

最佳答案

要获取响应正文和状态代码,您必须实现自己的ResponseWriter。 Here you can find full example

关于go - 如何从中间件记录响应主体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57369775/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com