我想问一下我们是否可以为Go http客户端创建“中间件”功能?示例我想添加一个日志功能,因此将记录每个发送的请求,或添加setAuthToken,以便将令牌添加到每个请求的标头中. 您可以使用
> 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() {
var c = &http.Client{Transport:LoggingRoundTripper{http.DefaultTransport}}
c.Get("https://www.google.com")
}
随意改变你想要的名字,我没想到它们很长时间.
