fshttp: allow Transport to be customized #3631

This commit is contained in:
Nick Craig-Wood 2019-10-16 11:21:26 +01:00
parent 543100070a
commit 0b6cdb7677
1 changed files with 66 additions and 53 deletions

View File

@ -127,9 +127,10 @@ func ResetTransport() {
noTransport = new(sync.Once) noTransport = new(sync.Once)
} }
// NewTransport returns an http.RoundTripper with the correct timeouts // NewTransportCustom returns an http.RoundTripper with the correct timeouts.
func NewTransport(ci *fs.ConfigInfo) http.RoundTripper { // The customize function is called if set to give the caller an opportunity to
(*noTransport).Do(func() { // customize any defaults in the Transport.
func NewTransportCustom(ci *fs.ConfigInfo, customize func(*http.Transport)) http.RoundTripper {
// Start with a sensible set of defaults then override. // Start with a sensible set of defaults then override.
// This also means we get new stuff when it gets added to go // This also means we get new stuff when it gets added to go
t := new(http.Transport) t := new(http.Transport)
@ -178,21 +179,33 @@ func NewTransport(ci *fs.ConfigInfo) http.RoundTripper {
} }
t.IdleConnTimeout = 60 * time.Second t.IdleConnTimeout = 60 * time.Second
t.ExpectContinueTimeout = ci.ConnectTimeout t.ExpectContinueTimeout = ci.ConnectTimeout
// customize the transport if required
if customize != nil {
customize(t)
}
// Wrap that http.Transport in our own transport // Wrap that http.Transport in our own transport
transport = newTransport(ci, t) return newTransport(ci, t)
}
// NewTransport returns an http.RoundTripper with the correct timeouts
func NewTransport(ci *fs.ConfigInfo) http.RoundTripper {
(*noTransport).Do(func() {
transport = NewTransportCustom(ci, nil)
}) })
return transport return transport
} }
// NewClient returns an http.Client with the correct timeouts // NewClient returns an http.Client with the correct timeouts
func NewClient(ci *fs.ConfigInfo) *http.Client { func NewClient(ci *fs.ConfigInfo) *http.Client {
transport := &http.Client{ client := &http.Client{
Transport: NewTransport(ci), Transport: NewTransport(ci),
} }
if ci.Cookie { if ci.Cookie {
transport.Jar = cookieJar client.Jar = cookieJar
} }
return transport return client
} }
// Transport is a our http Transport which wraps an http.Transport // Transport is a our http Transport which wraps an http.Transport