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