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