英文:
Go RoundTripper and Transport
问题
在Go语言中,RoundTripper是一个接口,定义了执行HTTP请求的方法。它是Transport类型的抽象,Transport是一个结构体,实现了RoundTripper接口。
RoundTripper接口定义了一个名为RoundTrip的方法,该方法接收一个Request参数并返回一个Response和一个error。它负责发送HTTP请求并返回响应。
Transport类型是RoundTripper接口的默认实现。在默认的Transport中,可以设置代理、连接超时、TLS握手超时等参数。
你提到的第一个代码片段是默认Transport的定义,其中包含了一些默认的参数设置。而第二个代码片段是自定义的Transport实例,你可以根据自己的需求设置不同的参数。
所以,RoundTripper和Transport是相关的,Transport是RoundTripper的具体实现。
英文:
I am having hard time understanding what we need RoundTripper for in Go.
https://golang.org/pkg/net/http/#RoundTripper
Explains the default Transport in Go:
var DefaultTransport RoundTripper = &Transport{
Proxy: ProxyFromEnvironment,
Dial: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).Dial,
TLSHandshakeTimeout: 10 * time.Second,
}
But what would be the difference between RoundTripper and this:
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
TLSHandshakeTimeout: timeout,
Dial: dialfunc,
DisableKeepAlives: true,
}
My question: is RoundTripper different than regular Transport?
答案1
得分: 22
我认为Volker在他对你问题的评论中说得很对。从我的角度来看,http.Transport提供了http.RoundTripper的实现,但你可以提供完全不同的实现,只要它实现了RoundTrip()方法。
许多人使用这种方式来添加速率限制(即它们提供一个实现,可能在内部使用http.Transport,但它们添加了限制程序发送或接收字节的速率的能力)。
英文:
I think Volker got it right in his comment on your question. From my perspective, http.Transport provides an implementation of http.RoundTripper, but you can provide your own that is completely different, as long as it implements RoundTrip().
A number of folks have used this as the way to add rate limiting (i.e. they provide an implementation which may use http.Transport under the covers, but they add the ability to constrain the rate at which your program sends or receives bytes).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论