Go RoundTripper and Transport

user2671513 picture user2671513 · Nov 3, 2014 · Viewed 14k times · Source

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?

Answer

James Synge picture James Synge · Nov 3, 2014

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