请问我们是否可以为Go http客户端创建"中间件"功能?例如,我想添加一个日志(log)函数,以便记录每个发送的请求,或者添加setAuthToken,以便将令牌添加到每个请求的头部.
请问我们是否可以为Go http客户端创建"中间件"功能?例如,我想添加一个日志(log)函数,以便记录每个发送的请求,或者添加setAuthToken,以便将令牌添加到每个请求的头部.
您可以在HTTP客户端中使用Transport
参数来实现此效果,并使用合成模式,使用以下事实:
http.Client.Transport
定义了处理所有HTTP请求的函数;http.Client.Transport
具有接口类型http.RoundTripper
,因此可以用您自己的实现替换;例如:
package main
import (
"fmt"
"net/http"
)
// This type implements the http.RoundTripper interface
type LoggingRoundTripper struct {
Proxied http.RoundTripper
}
func (lrt LoggingRoundTripper) RoundTrip(req *http.Request) (res *http.Response, e error) {
// Do "before sending requests" actions here.
fmt.Printf("Sending request to %v\n", req.URL)
// Send the request, get the response (or the error)
res, e = lrt.Proxied.RoundTrip(req)
// Handle the result.
if (e != nil) {
fmt.Printf("Error: %v", e)
} else {
fmt.Printf("Received %v response\n", res.Status)
}
return
}
func main() {
httpClient := &http.Client{
Transport: LoggingRoundTripper{http.DefaultTransport},
}
httpClient.Get("https://example.com/")
}
你想改名字就改吧,我没想太久.