27

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?

nemo
  • 55,207
  • 13
  • 135
  • 135
  • 2
    Do you want to know what `RoundTripper` is for or do you want to know why `DefaultTransport` has the type `RoundTripper`? Because the interface `RoundTripper` exists to do round trips. – nemo Nov 03 '14 at 05:11
  • 1
    I want to know what RoundTripper is –  Nov 03 '14 at 06:29
  • 15
    From the documentation: "RoundTripper is an interface representing the ability to execute a single HTTP transaction, obtaining the Response for a given Request." It sits in between the low level stuff like dialing, tcp, etc. and the high level details of HTTP (redirects, etc.) RoundTrip is *the* method do do a single round trip of request sent to server, server answers with response. – Volker Nov 03 '14 at 07:36

1 Answers1

22

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

nemo
  • 55,207
  • 13
  • 135
  • 135
James Synge
  • 592
  • 5
  • 11