Go RoundTripper和Transport

huangapple go评论101阅读模式
英文:

Go RoundTripper and Transport

问题

在Go语言中,RoundTripper是一个接口,定义了执行HTTP请求的方法。它是Transport类型的抽象,Transport是一个结构体,实现了RoundTripper接口。

RoundTripper接口定义了一个名为RoundTrip的方法,该方法接收一个Request参数并返回一个Response和一个error。它负责发送HTTP请求并返回响应。

Transport类型是RoundTripper接口的默认实现。在默认的Transport中,可以设置代理、连接超时、TLS握手超时等参数。

你提到的第一个代码片段是默认Transport的定义,其中包含了一些默认的参数设置。而第二个代码片段是自定义的Transport实例,你可以根据自己的需求设置不同的参数。

所以,RoundTripperTransport是相关的,TransportRoundTripper的具体实现。

英文:

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

huangapple
  • 本文由 发表于 2014年11月3日 12:50:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/26707941.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定