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