github.com/geraldss/go/src@v0.0.0-20210511222824-ac7d0ebfc235/net/http/client.go (about)

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // HTTP client. See RFC 7230 through 7235.
     6  //
     7  // This is the high-level Client interface.
     8  // The low-level implementation is in transport.go.
     9  
    10  package http
    11  
    12  import (
    13  	"context"
    14  	"crypto/tls"
    15  	"encoding/base64"
    16  	"errors"
    17  	"fmt"
    18  	"io"
    19  	"log"
    20  	"net/url"
    21  	"reflect"
    22  	"sort"
    23  	"strings"
    24  	"sync"
    25  	"time"
    26  )
    27  
    28  // A Client is an HTTP client. Its zero value (DefaultClient) is a
    29  // usable client that uses DefaultTransport.
    30  //
    31  // The Client's Transport typically has internal state (cached TCP
    32  // connections), so Clients should be reused instead of created as
    33  // needed. Clients are safe for concurrent use by multiple goroutines.
    34  //
    35  // A Client is higher-level than a RoundTripper (such as Transport)
    36  // and additionally handles HTTP details such as cookies and
    37  // redirects.
    38  //
    39  // When following redirects, the Client will forward all headers set on the
    40  // initial Request except:
    41  //
    42  // • when forwarding sensitive headers like "Authorization",
    43  // "WWW-Authenticate", and "Cookie" to untrusted targets.
    44  // These headers will be ignored when following a redirect to a domain
    45  // that is not a subdomain match or exact match of the initial domain.
    46  // For example, a redirect from "foo.com" to either "foo.com" or "sub.foo.com"
    47  // will forward the sensitive headers, but a redirect to "bar.com" will not.
    48  //
    49  // • when forwarding the "Cookie" header with a non-nil cookie Jar.
    50  // Since each redirect may mutate the state of the cookie jar,
    51  // a redirect may possibly alter a cookie set in the initial request.
    52  // When forwarding the "Cookie" header, any mutated cookies will be omitted,
    53  // with the expectation that the Jar will insert those mutated cookies
    54  // with the updated values (assuming the origin matches).
    55  // If Jar is nil, the initial cookies are forwarded without change.
    56  //
    57  type Client struct {
    58  	// Transport specifies the mechanism by which individual
    59  	// HTTP requests are made.
    60  	// If nil, DefaultTransport is used.
    61  	Transport RoundTripper
    62  
    63  	// CheckRedirect specifies the policy for handling redirects.
    64  	// If CheckRedirect is not nil, the client calls it before
    65  	// following an HTTP redirect. The arguments req and via are
    66  	// the upcoming request and the requests made already, oldest
    67  	// first. If CheckRedirect returns an error, the Client's Get
    68  	// method returns both the previous Response (with its Body
    69  	// closed) and CheckRedirect's error (wrapped in a url.Error)
    70  	// instead of issuing the Request req.
    71  	// As a special case, if CheckRedirect returns ErrUseLastResponse,
    72  	// then the most recent response is returned with its body
    73  	// unclosed, along with a nil error.
    74  	//
    75  	// If CheckRedirect is nil, the Client uses its default policy,
    76  	// which is to stop after 10 consecutive requests.
    77  	CheckRedirect func(req *Request, via []*Request) error
    78  
    79  	// Jar specifies the cookie jar.
    80  	//
    81  	// The Jar is used to insert relevant cookies into every
    82  	// outbound Request and is updated with the cookie values
    83  	// of every inbound Response. The Jar is consulted for every
    84  	// redirect that the Client follows.
    85  	//
    86  	// If Jar is nil, cookies are only sent if they are explicitly
    87  	// set on the Request.
    88  	Jar CookieJar
    89  
    90  	// Timeout specifies a time limit for requests made by this
    91  	// Client. The timeout includes connection time, any
    92  	// redirects, and reading the response body. The timer remains
    93  	// running after Get, Head, Post, or Do return and will
    94  	// interrupt reading of the Response.Body.
    95  	//
    96  	// A Timeout of zero means no timeout.
    97  	//
    98  	// The Client cancels requests to the underlying Transport
    99  	// as if the Request's Context ended.
   100  	//
   101  	// For compatibility, the Client will also use the deprecated
   102  	// CancelRequest method on Transport if found. New
   103  	// RoundTripper implementations should use the Request's Context
   104  	// for cancellation instead of implementing CancelRequest.
   105  	Timeout time.Duration
   106  }
   107  
   108  // DefaultClient is the default Client and is used by Get, Head, and Post.
   109  var DefaultClient = &Client{}
   110  
   111  // RoundTripper is an interface representing the ability to execute a
   112  // single HTTP transaction, obtaining the Response for a given Request.
   113  //
   114  // A RoundTripper must be safe for concurrent use by multiple
   115  // goroutines.
   116  type RoundTripper interface {
   117  	// RoundTrip executes a single HTTP transaction, returning
   118  	// a Response for the provided Request.
   119  	//
   120  	// RoundTrip should not attempt to interpret the response. In
   121  	// particular, RoundTrip must return err == nil if it obtained
   122  	// a response, regardless of the response's HTTP status code.
   123  	// A non-nil err should be reserved for failure to obtain a
   124  	// response. Similarly, RoundTrip should not attempt to
   125  	// handle higher-level protocol details such as redirects,
   126  	// authentication, or cookies.
   127  	//
   128  	// RoundTrip should not modify the request, except for
   129  	// consuming and closing the Request's Body. RoundTrip may
   130  	// read fields of the request in a separate goroutine. Callers
   131  	// should not mutate or reuse the request until the Response's
   132  	// Body has been closed.
   133  	//
   134  	// RoundTrip must always close the body, including on errors,
   135  	// but depending on the implementation may do so in a separate
   136  	// goroutine even after RoundTrip returns. This means that
   137  	// callers wanting to reuse the body for subsequent requests
   138  	// must arrange to wait for the Close call before doing so.
   139  	//
   140  	// The Request's URL and Header fields must be initialized.
   141  	RoundTrip(*Request) (*Response, error)
   142  }
   143  
   144  // refererForURL returns a referer without any authentication info or
   145  // an empty string if lastReq scheme is https and newReq scheme is http.
   146  func refererForURL(lastReq, newReq *url.URL) string {
   147  	// https://tools.ietf.org/html/rfc7231#section-5.5.2
   148  	//   "Clients SHOULD NOT include a Referer header field in a
   149  	//    (non-secure) HTTP request if the referring page was
   150  	//    transferred with a secure protocol."
   151  	if lastReq.Scheme == "https" && newReq.Scheme == "http" {
   152  		return ""
   153  	}
   154  	referer := lastReq.String()
   155  	if lastReq.User != nil {
   156  		// This is not very efficient, but is the best we can
   157  		// do without:
   158  		// - introducing a new method on URL
   159  		// - creating a race condition
   160  		// - copying the URL struct manually, which would cause
   161  		//   maintenance problems down the line
   162  		auth := lastReq.User.String() + "@"
   163  		referer = strings.Replace(referer, auth, "", 1)
   164  	}
   165  	return referer
   166  }
   167  
   168  // didTimeout is non-nil only if err != nil.
   169  func (c *Client) send(req *Request, deadline time.Time) (resp *Response, didTimeout func() bool, err error) {
   170  	if c.Jar != nil {
   171  		for _, cookie := range c.Jar.Cookies(req.URL) {
   172  			req.AddCookie(cookie)
   173  		}
   174  	}
   175  	resp, didTimeout, err = send(req, c.transport(), deadline)
   176  	if err != nil {
   177  		return nil, didTimeout, err
   178  	}
   179  	if c.Jar != nil {
   180  		if rc := resp.Cookies(); len(rc) > 0 {
   181  			c.Jar.SetCookies(req.URL, rc)
   182  		}
   183  	}
   184  	return resp, nil, nil
   185  }
   186  
   187  func (c *Client) deadline() time.Time {
   188  	if c.Timeout > 0 {
   189  		return time.Now().Add(c.Timeout)
   190  	}
   191  	return time.Time{}
   192  }
   193  
   194  func (c *Client) transport() RoundTripper {
   195  	if c.Transport != nil {
   196  		return c.Transport
   197  	}
   198  	return DefaultTransport
   199  }
   200  
   201  // send issues an HTTP request.
   202  // Caller should close resp.Body when done reading from it.
   203  func send(ireq *Request, rt RoundTripper, deadline time.Time) (resp *Response, didTimeout func() bool, err error) {
   204  	req := ireq // req is either the original request, or a modified fork
   205  
   206  	if rt == nil {
   207  		req.closeBody()
   208  		return nil, alwaysFalse, errors.New("http: no Client.Transport or DefaultTransport")
   209  	}
   210  
   211  	if req.URL == nil {
   212  		req.closeBody()
   213  		return nil, alwaysFalse, errors.New("http: nil Request.URL")
   214  	}
   215  
   216  	if req.RequestURI != "" {
   217  		req.closeBody()
   218  		return nil, alwaysFalse, errors.New("http: Request.RequestURI can't be set in client requests")
   219  	}
   220  
   221  	// forkReq forks req into a shallow clone of ireq the first
   222  	// time it's called.
   223  	forkReq := func() {
   224  		if ireq == req {
   225  			req = new(Request)
   226  			*req = *ireq // shallow clone
   227  		}
   228  	}
   229  
   230  	// Most the callers of send (Get, Post, et al) don't need
   231  	// Headers, leaving it uninitialized. We guarantee to the
   232  	// Transport that this has been initialized, though.
   233  	if req.Header == nil {
   234  		forkReq()
   235  		req.Header = make(Header)
   236  	}
   237  
   238  	if u := req.URL.User; u != nil && req.Header.Get("Authorization") == "" {
   239  		username := u.Username()
   240  		password, _ := u.Password()
   241  		forkReq()
   242  		req.Header = cloneOrMakeHeader(ireq.Header)
   243  		req.Header.Set("Authorization", "Basic "+basicAuth(username, password))
   244  	}
   245  
   246  	if !deadline.IsZero() {
   247  		forkReq()
   248  	}
   249  	stopTimer, didTimeout := setRequestCancel(req, rt, deadline)
   250  
   251  	resp, err = rt.RoundTrip(req)
   252  	if err != nil {
   253  		stopTimer()
   254  		if resp != nil {
   255  			log.Printf("RoundTripper returned a response & error; ignoring response")
   256  		}
   257  		if tlsErr, ok := err.(tls.RecordHeaderError); ok {
   258  			// If we get a bad TLS record header, check to see if the
   259  			// response looks like HTTP and give a more helpful error.
   260  			// See golang.org/issue/11111.
   261  			if string(tlsErr.RecordHeader[:]) == "HTTP/" {
   262  				err = errors.New("http: server gave HTTP response to HTTPS client")
   263  			}
   264  		}
   265  		return nil, didTimeout, err
   266  	}
   267  	if resp == nil {
   268  		return nil, didTimeout, fmt.Errorf("http: RoundTripper implementation (%T) returned a nil *Response with a nil error", rt)
   269  	}
   270  	if resp.Body == nil {
   271  		// The documentation on the Body field says “The http Client and Transport
   272  		// guarantee that Body is always non-nil, even on responses without a body
   273  		// or responses with a zero-length body.” Unfortunately, we didn't document
   274  		// that same constraint for arbitrary RoundTripper implementations, and
   275  		// RoundTripper implementations in the wild (mostly in tests) assume that
   276  		// they can use a nil Body to mean an empty one (similar to Request.Body).
   277  		// (See https://golang.org/issue/38095.)
   278  		//
   279  		// If the ContentLength allows the Body to be empty, fill in an empty one
   280  		// here to ensure that it is non-nil.
   281  		if resp.ContentLength > 0 && req.Method != "HEAD" {
   282  			return nil, didTimeout, fmt.Errorf("http: RoundTripper implementation (%T) returned a *Response with content length %d but a nil Body", rt, resp.ContentLength)
   283  		}
   284  		resp.Body = io.NopCloser(strings.NewReader(""))
   285  	}
   286  	if !deadline.IsZero() {
   287  		resp.Body = &cancelTimerBody{
   288  			stop:          stopTimer,
   289  			rc:            resp.Body,
   290  			reqDidTimeout: didTimeout,
   291  		}
   292  	}
   293  	return resp, nil, nil
   294  }
   295  
   296  // timeBeforeContextDeadline reports whether the non-zero Time t is
   297  // before ctx's deadline, if any. If ctx does not have a deadline, it
   298  // always reports true (the deadline is considered infinite).
   299  func timeBeforeContextDeadline(t time.Time, ctx context.Context) bool {
   300  	d, ok := ctx.Deadline()
   301  	if !ok {
   302  		return true
   303  	}
   304  	return t.Before(d)
   305  }
   306  
   307  // knownRoundTripperImpl reports whether rt is a RoundTripper that's
   308  // maintained by the Go team and known to implement the latest
   309  // optional semantics (notably contexts). The Request is used
   310  // to check whether this particular request is using an alternate protocol,
   311  // in which case we need to check the RoundTripper for that protocol.
   312  func knownRoundTripperImpl(rt RoundTripper, req *Request) bool {
   313  	switch t := rt.(type) {
   314  	case *Transport:
   315  		if altRT := t.alternateRoundTripper(req); altRT != nil {
   316  			return knownRoundTripperImpl(altRT, req)
   317  		}
   318  		return true
   319  	case *http2Transport, http2noDialH2RoundTripper:
   320  		return true
   321  	}
   322  	// There's a very minor chance of a false positive with this.
   323  	// Instead of detecting our golang.org/x/net/http2.Transport,
   324  	// it might detect a Transport type in a different http2
   325  	// package. But I know of none, and the only problem would be
   326  	// some temporarily leaked goroutines if the transport didn't
   327  	// support contexts. So this is a good enough heuristic:
   328  	if reflect.TypeOf(rt).String() == "*http2.Transport" {
   329  		return true
   330  	}
   331  	return false
   332  }
   333  
   334  // setRequestCancel sets req.Cancel and adds a deadline context to req
   335  // if deadline is non-zero. The RoundTripper's type is used to
   336  // determine whether the legacy CancelRequest behavior should be used.
   337  //
   338  // As background, there are three ways to cancel a request:
   339  // First was Transport.CancelRequest. (deprecated)
   340  // Second was Request.Cancel.
   341  // Third was Request.Context.
   342  // This function populates the second and third, and uses the first if it really needs to.
   343  func setRequestCancel(req *Request, rt RoundTripper, deadline time.Time) (stopTimer func(), didTimeout func() bool) {
   344  	if deadline.IsZero() {
   345  		return nop, alwaysFalse
   346  	}
   347  	knownTransport := knownRoundTripperImpl(rt, req)
   348  	oldCtx := req.Context()
   349  
   350  	if req.Cancel == nil && knownTransport {
   351  		// If they already had a Request.Context that's
   352  		// expiring sooner, do nothing:
   353  		if !timeBeforeContextDeadline(deadline, oldCtx) {
   354  			return nop, alwaysFalse
   355  		}
   356  
   357  		var cancelCtx func()
   358  		req.ctx, cancelCtx = context.WithDeadline(oldCtx, deadline)
   359  		return cancelCtx, func() bool { return time.Now().After(deadline) }
   360  	}
   361  	initialReqCancel := req.Cancel // the user's original Request.Cancel, if any
   362  
   363  	var cancelCtx func()
   364  	if oldCtx := req.Context(); timeBeforeContextDeadline(deadline, oldCtx) {
   365  		req.ctx, cancelCtx = context.WithDeadline(oldCtx, deadline)
   366  	}
   367  
   368  	cancel := make(chan struct{})
   369  	req.Cancel = cancel
   370  
   371  	doCancel := func() {
   372  		// The second way in the func comment above:
   373  		close(cancel)
   374  		// The first way, used only for RoundTripper
   375  		// implementations written before Go 1.5 or Go 1.6.
   376  		type canceler interface{ CancelRequest(*Request) }
   377  		if v, ok := rt.(canceler); ok {
   378  			v.CancelRequest(req)
   379  		}
   380  	}
   381  
   382  	stopTimerCh := make(chan struct{})
   383  	var once sync.Once
   384  	stopTimer = func() {
   385  		once.Do(func() {
   386  			close(stopTimerCh)
   387  			if cancelCtx != nil {
   388  				cancelCtx()
   389  			}
   390  		})
   391  	}
   392  
   393  	timer := time.NewTimer(time.Until(deadline))
   394  	var timedOut atomicBool
   395  
   396  	go func() {
   397  		select {
   398  		case <-initialReqCancel:
   399  			doCancel()
   400  			timer.Stop()
   401  		case <-timer.C:
   402  			timedOut.setTrue()
   403  			doCancel()
   404  		case <-stopTimerCh:
   405  			timer.Stop()
   406  		}
   407  	}()
   408  
   409  	return stopTimer, timedOut.isSet
   410  }
   411  
   412  // See 2 (end of page 4) https://www.ietf.org/rfc/rfc2617.txt
   413  // "To receive authorization, the client sends the userid and password,
   414  // separated by a single colon (":") character, within a base64
   415  // encoded string in the credentials."
   416  // It is not meant to be urlencoded.
   417  func basicAuth(username, password string) string {
   418  	auth := username + ":" + password
   419  	return base64.StdEncoding.EncodeToString([]byte(auth))
   420  }
   421  
   422  // Get issues a GET to the specified URL. If the response is one of
   423  // the following redirect codes, Get follows the redirect, up to a
   424  // maximum of 10 redirects:
   425  //
   426  //    301 (Moved Permanently)
   427  //    302 (Found)
   428  //    303 (See Other)
   429  //    307 (Temporary Redirect)
   430  //    308 (Permanent Redirect)
   431  //
   432  // An error is returned if there were too many redirects or if there
   433  // was an HTTP protocol error. A non-2xx response doesn't cause an
   434  // error. Any returned error will be of type *url.Error. The url.Error
   435  // value's Timeout method will report true if request timed out or was
   436  // canceled.
   437  //
   438  // When err is nil, resp always contains a non-nil resp.Body.
   439  // Caller should close resp.Body when done reading from it.
   440  //
   441  // Get is a wrapper around DefaultClient.Get.
   442  //
   443  // To make a request with custom headers, use NewRequest and
   444  // DefaultClient.Do.
   445  func Get(url string) (resp *Response, err error) {
   446  	return DefaultClient.Get(url)
   447  }
   448  
   449  // Get issues a GET to the specified URL. If the response is one of the
   450  // following redirect codes, Get follows the redirect after calling the
   451  // Client's CheckRedirect function:
   452  //
   453  //    301 (Moved Permanently)
   454  //    302 (Found)
   455  //    303 (See Other)
   456  //    307 (Temporary Redirect)
   457  //    308 (Permanent Redirect)
   458  //
   459  // An error is returned if the Client's CheckRedirect function fails
   460  // or if there was an HTTP protocol error. A non-2xx response doesn't
   461  // cause an error. Any returned error will be of type *url.Error. The
   462  // url.Error value's Timeout method will report true if the request
   463  // timed out.
   464  //
   465  // When err is nil, resp always contains a non-nil resp.Body.
   466  // Caller should close resp.Body when done reading from it.
   467  //
   468  // To make a request with custom headers, use NewRequest and Client.Do.
   469  func (c *Client) Get(url string) (resp *Response, err error) {
   470  	req, err := NewRequest("GET", url, nil)
   471  	if err != nil {
   472  		return nil, err
   473  	}
   474  	return c.Do(req)
   475  }
   476  
   477  func alwaysFalse() bool { return false }
   478  
   479  // ErrUseLastResponse can be returned by Client.CheckRedirect hooks to
   480  // control how redirects are processed. If returned, the next request
   481  // is not sent and the most recent response is returned with its body
   482  // unclosed.
   483  var ErrUseLastResponse = errors.New("net/http: use last response")
   484  
   485  // checkRedirect calls either the user's configured CheckRedirect
   486  // function, or the default.
   487  func (c *Client) checkRedirect(req *Request, via []*Request) error {
   488  	fn := c.CheckRedirect
   489  	if fn == nil {
   490  		fn = defaultCheckRedirect
   491  	}
   492  	return fn(req, via)
   493  }
   494  
   495  // redirectBehavior describes what should happen when the
   496  // client encounters a 3xx status code from the server
   497  func redirectBehavior(reqMethod string, resp *Response, ireq *Request) (redirectMethod string, shouldRedirect, includeBody bool) {
   498  	switch resp.StatusCode {
   499  	case 301, 302, 303:
   500  		redirectMethod = reqMethod
   501  		shouldRedirect = true
   502  		includeBody = false
   503  
   504  		// RFC 2616 allowed automatic redirection only with GET and
   505  		// HEAD requests. RFC 7231 lifts this restriction, but we still
   506  		// restrict other methods to GET to maintain compatibility.
   507  		// See Issue 18570.
   508  		if reqMethod != "GET" && reqMethod != "HEAD" {
   509  			redirectMethod = "GET"
   510  		}
   511  	case 307, 308:
   512  		redirectMethod = reqMethod
   513  		shouldRedirect = true
   514  		includeBody = true
   515  
   516  		// Treat 307 and 308 specially, since they're new in
   517  		// Go 1.8, and they also require re-sending the request body.
   518  		if resp.Header.Get("Location") == "" {
   519  			// 308s have been observed in the wild being served
   520  			// without Location headers. Since Go 1.7 and earlier
   521  			// didn't follow these codes, just stop here instead
   522  			// of returning an error.
   523  			// See Issue 17773.
   524  			shouldRedirect = false
   525  			break
   526  		}
   527  		if ireq.GetBody == nil && ireq.outgoingLength() != 0 {
   528  			// We had a request body, and 307/308 require
   529  			// re-sending it, but GetBody is not defined. So just
   530  			// return this response to the user instead of an
   531  			// error, like we did in Go 1.7 and earlier.
   532  			shouldRedirect = false
   533  		}
   534  	}
   535  	return redirectMethod, shouldRedirect, includeBody
   536  }
   537  
   538  // urlErrorOp returns the (*url.Error).Op value to use for the
   539  // provided (*Request).Method value.
   540  func urlErrorOp(method string) string {
   541  	if method == "" {
   542  		return "Get"
   543  	}
   544  	return method[:1] + strings.ToLower(method[1:])
   545  }
   546  
   547  // Do sends an HTTP request and returns an HTTP response, following
   548  // policy (such as redirects, cookies, auth) as configured on the
   549  // client.
   550  //
   551  // An error is returned if caused by client policy (such as
   552  // CheckRedirect), or failure to speak HTTP (such as a network
   553  // connectivity problem). A non-2xx status code doesn't cause an
   554  // error.
   555  //
   556  // If the returned error is nil, the Response will contain a non-nil
   557  // Body which the user is expected to close. If the Body is not both
   558  // read to EOF and closed, the Client's underlying RoundTripper
   559  // (typically Transport) may not be able to re-use a persistent TCP
   560  // connection to the server for a subsequent "keep-alive" request.
   561  //
   562  // The request Body, if non-nil, will be closed by the underlying
   563  // Transport, even on errors.
   564  //
   565  // On error, any Response can be ignored. A non-nil Response with a
   566  // non-nil error only occurs when CheckRedirect fails, and even then
   567  // the returned Response.Body is already closed.
   568  //
   569  // Generally Get, Post, or PostForm will be used instead of Do.
   570  //
   571  // If the server replies with a redirect, the Client first uses the
   572  // CheckRedirect function to determine whether the redirect should be
   573  // followed. If permitted, a 301, 302, or 303 redirect causes
   574  // subsequent requests to use HTTP method GET
   575  // (or HEAD if the original request was HEAD), with no body.
   576  // A 307 or 308 redirect preserves the original HTTP method and body,
   577  // provided that the Request.GetBody function is defined.
   578  // The NewRequest function automatically sets GetBody for common
   579  // standard library body types.
   580  //
   581  // Any returned error will be of type *url.Error. The url.Error
   582  // value's Timeout method will report true if request timed out or was
   583  // canceled.
   584  func (c *Client) Do(req *Request) (*Response, error) {
   585  	return c.do(req)
   586  }
   587  
   588  var testHookClientDoResult func(retres *Response, reterr error)
   589  
   590  func (c *Client) do(req *Request) (retres *Response, reterr error) {
   591  	if testHookClientDoResult != nil {
   592  		defer func() { testHookClientDoResult(retres, reterr) }()
   593  	}
   594  	if req.URL == nil {
   595  		req.closeBody()
   596  		return nil, &url.Error{
   597  			Op:  urlErrorOp(req.Method),
   598  			Err: errors.New("http: nil Request.URL"),
   599  		}
   600  	}
   601  
   602  	var (
   603  		deadline      = c.deadline()
   604  		reqs          []*Request
   605  		resp          *Response
   606  		copyHeaders   = c.makeHeadersCopier(req)
   607  		reqBodyClosed = false // have we closed the current req.Body?
   608  
   609  		// Redirect behavior:
   610  		redirectMethod string
   611  		includeBody    bool
   612  	)
   613  	uerr := func(err error) error {
   614  		// the body may have been closed already by c.send()
   615  		if !reqBodyClosed {
   616  			req.closeBody()
   617  		}
   618  		var urlStr string
   619  		if resp != nil && resp.Request != nil {
   620  			urlStr = stripPassword(resp.Request.URL)
   621  		} else {
   622  			urlStr = stripPassword(req.URL)
   623  		}
   624  		return &url.Error{
   625  			Op:  urlErrorOp(reqs[0].Method),
   626  			URL: urlStr,
   627  			Err: err,
   628  		}
   629  	}
   630  	for {
   631  		// For all but the first request, create the next
   632  		// request hop and replace req.
   633  		if len(reqs) > 0 {
   634  			loc := resp.Header.Get("Location")
   635  			if loc == "" {
   636  				resp.closeBody()
   637  				return nil, uerr(fmt.Errorf("%d response missing Location header", resp.StatusCode))
   638  			}
   639  			u, err := req.URL.Parse(loc)
   640  			if err != nil {
   641  				resp.closeBody()
   642  				return nil, uerr(fmt.Errorf("failed to parse Location header %q: %v", loc, err))
   643  			}
   644  			host := ""
   645  			if req.Host != "" && req.Host != req.URL.Host {
   646  				// If the caller specified a custom Host header and the
   647  				// redirect location is relative, preserve the Host header
   648  				// through the redirect. See issue #22233.
   649  				if u, _ := url.Parse(loc); u != nil && !u.IsAbs() {
   650  					host = req.Host
   651  				}
   652  			}
   653  			ireq := reqs[0]
   654  			req = &Request{
   655  				Method:   redirectMethod,
   656  				Response: resp,
   657  				URL:      u,
   658  				Header:   make(Header),
   659  				Host:     host,
   660  				Cancel:   ireq.Cancel,
   661  				ctx:      ireq.ctx,
   662  			}
   663  			if includeBody && ireq.GetBody != nil {
   664  				req.Body, err = ireq.GetBody()
   665  				if err != nil {
   666  					resp.closeBody()
   667  					return nil, uerr(err)
   668  				}
   669  				req.ContentLength = ireq.ContentLength
   670  			}
   671  
   672  			// Copy original headers before setting the Referer,
   673  			// in case the user set Referer on their first request.
   674  			// If they really want to override, they can do it in
   675  			// their CheckRedirect func.
   676  			copyHeaders(req)
   677  
   678  			// Add the Referer header from the most recent
   679  			// request URL to the new one, if it's not https->http:
   680  			if ref := refererForURL(reqs[len(reqs)-1].URL, req.URL); ref != "" {
   681  				req.Header.Set("Referer", ref)
   682  			}
   683  			err = c.checkRedirect(req, reqs)
   684  
   685  			// Sentinel error to let users select the
   686  			// previous response, without closing its
   687  			// body. See Issue 10069.
   688  			if err == ErrUseLastResponse {
   689  				return resp, nil
   690  			}
   691  
   692  			// Close the previous response's body. But
   693  			// read at least some of the body so if it's
   694  			// small the underlying TCP connection will be
   695  			// re-used. No need to check for errors: if it
   696  			// fails, the Transport won't reuse it anyway.
   697  			const maxBodySlurpSize = 2 << 10
   698  			if resp.ContentLength == -1 || resp.ContentLength <= maxBodySlurpSize {
   699  				io.CopyN(io.Discard, resp.Body, maxBodySlurpSize)
   700  			}
   701  			resp.Body.Close()
   702  
   703  			if err != nil {
   704  				// Special case for Go 1 compatibility: return both the response
   705  				// and an error if the CheckRedirect function failed.
   706  				// See https://golang.org/issue/3795
   707  				// The resp.Body has already been closed.
   708  				ue := uerr(err)
   709  				ue.(*url.Error).URL = loc
   710  				return resp, ue
   711  			}
   712  		}
   713  
   714  		reqs = append(reqs, req)
   715  		var err error
   716  		var didTimeout func() bool
   717  		if resp, didTimeout, err = c.send(req, deadline); err != nil {
   718  			// c.send() always closes req.Body
   719  			reqBodyClosed = true
   720  			if !deadline.IsZero() && didTimeout() {
   721  				err = &httpError{
   722  					// TODO: early in cycle: s/Client.Timeout exceeded/timeout or context cancellation/
   723  					err:     err.Error() + " (Client.Timeout exceeded while awaiting headers)",
   724  					timeout: true,
   725  				}
   726  			}
   727  			return nil, uerr(err)
   728  		}
   729  
   730  		var shouldRedirect bool
   731  		redirectMethod, shouldRedirect, includeBody = redirectBehavior(req.Method, resp, reqs[0])
   732  		if !shouldRedirect {
   733  			return resp, nil
   734  		}
   735  
   736  		req.closeBody()
   737  	}
   738  }
   739  
   740  // makeHeadersCopier makes a function that copies headers from the
   741  // initial Request, ireq. For every redirect, this function must be called
   742  // so that it can copy headers into the upcoming Request.
   743  func (c *Client) makeHeadersCopier(ireq *Request) func(*Request) {
   744  	// The headers to copy are from the very initial request.
   745  	// We use a closured callback to keep a reference to these original headers.
   746  	var (
   747  		ireqhdr  = cloneOrMakeHeader(ireq.Header)
   748  		icookies map[string][]*Cookie
   749  	)
   750  	if c.Jar != nil && ireq.Header.Get("Cookie") != "" {
   751  		icookies = make(map[string][]*Cookie)
   752  		for _, c := range ireq.Cookies() {
   753  			icookies[c.Name] = append(icookies[c.Name], c)
   754  		}
   755  	}
   756  
   757  	preq := ireq // The previous request
   758  	return func(req *Request) {
   759  		// If Jar is present and there was some initial cookies provided
   760  		// via the request header, then we may need to alter the initial
   761  		// cookies as we follow redirects since each redirect may end up
   762  		// modifying a pre-existing cookie.
   763  		//
   764  		// Since cookies already set in the request header do not contain
   765  		// information about the original domain and path, the logic below
   766  		// assumes any new set cookies override the original cookie
   767  		// regardless of domain or path.
   768  		//
   769  		// See https://golang.org/issue/17494
   770  		if c.Jar != nil && icookies != nil {
   771  			var changed bool
   772  			resp := req.Response // The response that caused the upcoming redirect
   773  			for _, c := range resp.Cookies() {
   774  				if _, ok := icookies[c.Name]; ok {
   775  					delete(icookies, c.Name)
   776  					changed = true
   777  				}
   778  			}
   779  			if changed {
   780  				ireqhdr.Del("Cookie")
   781  				var ss []string
   782  				for _, cs := range icookies {
   783  					for _, c := range cs {
   784  						ss = append(ss, c.Name+"="+c.Value)
   785  					}
   786  				}
   787  				sort.Strings(ss) // Ensure deterministic headers
   788  				ireqhdr.Set("Cookie", strings.Join(ss, "; "))
   789  			}
   790  		}
   791  
   792  		// Copy the initial request's Header values
   793  		// (at least the safe ones).
   794  		for k, vv := range ireqhdr {
   795  			if shouldCopyHeaderOnRedirect(k, preq.URL, req.URL) {
   796  				req.Header[k] = vv
   797  			}
   798  		}
   799  
   800  		preq = req // Update previous Request with the current request
   801  	}
   802  }
   803  
   804  func defaultCheckRedirect(req *Request, via []*Request) error {
   805  	if len(via) >= 10 {
   806  		return errors.New("stopped after 10 redirects")
   807  	}
   808  	return nil
   809  }
   810  
   811  // Post issues a POST to the specified URL.
   812  //
   813  // Caller should close resp.Body when done reading from it.
   814  //
   815  // If the provided body is an io.Closer, it is closed after the
   816  // request.
   817  //
   818  // Post is a wrapper around DefaultClient.Post.
   819  //
   820  // To set custom headers, use NewRequest and DefaultClient.Do.
   821  //
   822  // See the Client.Do method documentation for details on how redirects
   823  // are handled.
   824  func Post(url, contentType string, body io.Reader) (resp *Response, err error) {
   825  	return DefaultClient.Post(url, contentType, body)
   826  }
   827  
   828  // Post issues a POST to the specified URL.
   829  //
   830  // Caller should close resp.Body when done reading from it.
   831  //
   832  // If the provided body is an io.Closer, it is closed after the
   833  // request.
   834  //
   835  // To set custom headers, use NewRequest and Client.Do.
   836  //
   837  // See the Client.Do method documentation for details on how redirects
   838  // are handled.
   839  func (c *Client) Post(url, contentType string, body io.Reader) (resp *Response, err error) {
   840  	req, err := NewRequest("POST", url, body)
   841  	if err != nil {
   842  		return nil, err
   843  	}
   844  	req.Header.Set("Content-Type", contentType)
   845  	return c.Do(req)
   846  }
   847  
   848  // PostForm issues a POST to the specified URL, with data's keys and
   849  // values URL-encoded as the request body.
   850  //
   851  // The Content-Type header is set to application/x-www-form-urlencoded.
   852  // To set other headers, use NewRequest and DefaultClient.Do.
   853  //
   854  // When err is nil, resp always contains a non-nil resp.Body.
   855  // Caller should close resp.Body when done reading from it.
   856  //
   857  // PostForm is a wrapper around DefaultClient.PostForm.
   858  //
   859  // See the Client.Do method documentation for details on how redirects
   860  // are handled.
   861  func PostForm(url string, data url.Values) (resp *Response, err error) {
   862  	return DefaultClient.PostForm(url, data)
   863  }
   864  
   865  // PostForm issues a POST to the specified URL,
   866  // with data's keys and values URL-encoded as the request body.
   867  //
   868  // The Content-Type header is set to application/x-www-form-urlencoded.
   869  // To set other headers, use NewRequest and Client.Do.
   870  //
   871  // When err is nil, resp always contains a non-nil resp.Body.
   872  // Caller should close resp.Body when done reading from it.
   873  //
   874  // See the Client.Do method documentation for details on how redirects
   875  // are handled.
   876  func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error) {
   877  	return c.Post(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
   878  }
   879  
   880  // Head issues a HEAD to the specified URL. If the response is one of
   881  // the following redirect codes, Head follows the redirect, up to a
   882  // maximum of 10 redirects:
   883  //
   884  //    301 (Moved Permanently)
   885  //    302 (Found)
   886  //    303 (See Other)
   887  //    307 (Temporary Redirect)
   888  //    308 (Permanent Redirect)
   889  //
   890  // Head is a wrapper around DefaultClient.Head
   891  func Head(url string) (resp *Response, err error) {
   892  	return DefaultClient.Head(url)
   893  }
   894  
   895  // Head issues a HEAD to the specified URL. If the response is one of the
   896  // following redirect codes, Head follows the redirect after calling the
   897  // Client's CheckRedirect function:
   898  //
   899  //    301 (Moved Permanently)
   900  //    302 (Found)
   901  //    303 (See Other)
   902  //    307 (Temporary Redirect)
   903  //    308 (Permanent Redirect)
   904  func (c *Client) Head(url string) (resp *Response, err error) {
   905  	req, err := NewRequest("HEAD", url, nil)
   906  	if err != nil {
   907  		return nil, err
   908  	}
   909  	return c.Do(req)
   910  }
   911  
   912  // CloseIdleConnections closes any connections on its Transport which
   913  // were previously connected from previous requests but are now
   914  // sitting idle in a "keep-alive" state. It does not interrupt any
   915  // connections currently in use.
   916  //
   917  // If the Client's Transport does not have a CloseIdleConnections method
   918  // then this method does nothing.
   919  func (c *Client) CloseIdleConnections() {
   920  	type closeIdler interface {
   921  		CloseIdleConnections()
   922  	}
   923  	if tr, ok := c.transport().(closeIdler); ok {
   924  		tr.CloseIdleConnections()
   925  	}
   926  }
   927  
   928  // cancelTimerBody is an io.ReadCloser that wraps rc with two features:
   929  // 1) on Read error or close, the stop func is called.
   930  // 2) On Read failure, if reqDidTimeout is true, the error is wrapped and
   931  //    marked as net.Error that hit its timeout.
   932  type cancelTimerBody struct {
   933  	stop          func() // stops the time.Timer waiting to cancel the request
   934  	rc            io.ReadCloser
   935  	reqDidTimeout func() bool
   936  }
   937  
   938  func (b *cancelTimerBody) Read(p []byte) (n int, err error) {
   939  	n, err = b.rc.Read(p)
   940  	if err == nil {
   941  		return n, nil
   942  	}
   943  	b.stop()
   944  	if err == io.EOF {
   945  		return n, err
   946  	}
   947  	if b.reqDidTimeout() {
   948  		err = &httpError{
   949  			err:     err.Error() + " (Client.Timeout or context cancellation while reading body)",
   950  			timeout: true,
   951  		}
   952  	}
   953  	return n, err
   954  }
   955  
   956  func (b *cancelTimerBody) Close() error {
   957  	err := b.rc.Close()
   958  	b.stop()
   959  	return err
   960  }
   961  
   962  func shouldCopyHeaderOnRedirect(headerKey string, initial, dest *url.URL) bool {
   963  	switch CanonicalHeaderKey(headerKey) {
   964  	case "Authorization", "Www-Authenticate", "Cookie", "Cookie2":
   965  		// Permit sending auth/cookie headers from "foo.com"
   966  		// to "sub.foo.com".
   967  
   968  		// Note that we don't send all cookies to subdomains
   969  		// automatically. This function is only used for
   970  		// Cookies set explicitly on the initial outgoing
   971  		// client request. Cookies automatically added via the
   972  		// CookieJar mechanism continue to follow each
   973  		// cookie's scope as set by Set-Cookie. But for
   974  		// outgoing requests with the Cookie header set
   975  		// directly, we don't know their scope, so we assume
   976  		// it's for *.domain.com.
   977  
   978  		ihost := canonicalAddr(initial)
   979  		dhost := canonicalAddr(dest)
   980  		return isDomainOrSubdomain(dhost, ihost)
   981  	}
   982  	// All other headers are copied:
   983  	return true
   984  }
   985  
   986  // isDomainOrSubdomain reports whether sub is a subdomain (or exact
   987  // match) of the parent domain.
   988  //
   989  // Both domains must already be in canonical form.
   990  func isDomainOrSubdomain(sub, parent string) bool {
   991  	if sub == parent {
   992  		return true
   993  	}
   994  	// If sub is "foo.example.com" and parent is "example.com",
   995  	// that means sub must end in "."+parent.
   996  	// Do it without allocating.
   997  	if !strings.HasSuffix(sub, parent) {
   998  		return false
   999  	}
  1000  	return sub[len(sub)-len(parent)-1] == '.'
  1001  }
  1002  
  1003  func stripPassword(u *url.URL) string {
  1004  	_, passSet := u.User.Password()
  1005  	if passSet {
  1006  		return strings.Replace(u.String(), u.User.String()+"@", u.User.Username()+":***@", 1)
  1007  	}
  1008  	return u.String()
  1009  }