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