【问题标题】:Logging All HTTP Request and Response from done through an HTTP Client通过 HTTP 客户端记录所有 HTTP 请求和响应
【发布时间】:2021-11-15 11:04:37
【问题描述】:

我有以下简单的http.Client

import (
 "net/http"
 "log"
)
...
func main() {
   ...
   link = "http://example.com"
   method = "GET"
   req, _ := http.NewRequest(method, link, nil)

   client := &http.Client{}

   myZapLogger.Info("Sending a %s request to %s\n", method, link)

   resp, err := client.Do(req)
   if err != nil {
      myZapLogger.Error(..., err) // I'm logging rather than fatal-ing or so
   } else { 
      myZapLogger.Info("Received a %d on request X", resp.StatusCode)
   }
   ...
}

...

我一直在寻找一种方法来通过钩子(左右)为每个请求执行上述操作,以便每次都自动触发。我可以编写一个包含所有内容的函数,但是在我将 http 客户端传递给其他包的情况下,我将无法以这种方式控制/记录此类请求(例如 aws-go-sdk)。

有没有办法通过上下文或将钩子附加到客户端来做到这一点?

谢谢

【问题讨论】:

  • 修饰 http.Client.Transport 中的 http.RoundTripper 接口。
  • 是的。我刚刚意识到这样做是可行的;如果您愿意,请随时提出答案。

标签: http go logging


【解决方案1】:

eudore 的评论回答了这个问题;我将其放入代码中:

type MyRoundTripper struct {}

func (t MyRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
    
    // Do work before the request is sent

    resp, err := http.DefaultTransport.RoundTrip(req)
    if err != nil {
        return resp, err
    }
    
    // Do work after the response is received

    return resp, err
}

要使用它,您只需将它传递给您的 HTTP 客户端:

rt := MyRoundTripper{}
client := http.Client{Transport: rt}

【讨论】:

    猜你喜欢
    • 2012-09-15
    • 1970-01-01
    • 2015-12-05
    • 2023-01-13
    • 2011-02-01
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多