github.com/fjballest/golang@v0.0.0-20151209143359-e4c5fe594ca8/src/net/http/client.go (about) 1 // Copyright 2009 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // HTTP client. See RFC 2616. 6 // 7 // This is the high-level Client interface. 8 // The low-level implementation is in transport.go. 9 10 package http 11 12 import ( 13 "crypto/tls" 14 "encoding/base64" 15 "errors" 16 "fmt" 17 "io" 18 "io/ioutil" 19 "log" 20 "net/url" 21 "strings" 22 "sync" 23 "sync/atomic" 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 type Client struct { 38 // Transport specifies the mechanism by which individual 39 // HTTP requests are made. 40 // If nil, DefaultTransport is used. 41 Transport RoundTripper 42 43 // CheckRedirect specifies the policy for handling redirects. 44 // If CheckRedirect is not nil, the client calls it before 45 // following an HTTP redirect. The arguments req and via are 46 // the upcoming request and the requests made already, oldest 47 // first. If CheckRedirect returns an error, the Client's Get 48 // method returns both the previous Response and 49 // CheckRedirect's error (wrapped in a url.Error) instead of 50 // issuing the Request req. 51 // 52 // If CheckRedirect is nil, the Client uses its default policy, 53 // which is to stop after 10 consecutive requests. 54 CheckRedirect func(req *Request, via []*Request) error 55 56 // Jar specifies the cookie jar. 57 // If Jar is nil, cookies are not sent in requests and ignored 58 // in responses. 59 Jar CookieJar 60 61 // Timeout specifies a time limit for requests made by this 62 // Client. The timeout includes connection time, any 63 // redirects, and reading the response body. The timer remains 64 // running after Get, Head, Post, or Do return and will 65 // interrupt reading of the Response.Body. 66 // 67 // A Timeout of zero means no timeout. 68 // 69 // The Client's Transport must support the CancelRequest 70 // method or Client will return errors when attempting to make 71 // a request with Get, Head, Post, or Do. Client's default 72 // Transport (DefaultTransport) supports CancelRequest. 73 Timeout time.Duration 74 } 75 76 // DefaultClient is the default Client and is used by Get, Head, and Post. 77 var DefaultClient = &Client{} 78 79 // RoundTripper is an interface representing the ability to execute a 80 // single HTTP transaction, obtaining the Response for a given Request. 81 // 82 // A RoundTripper must be safe for concurrent use by multiple 83 // goroutines. 84 type RoundTripper interface { 85 // RoundTrip executes a single HTTP transaction, returning 86 // the Response for the request req. RoundTrip should not 87 // attempt to interpret the response. In particular, 88 // RoundTrip must return err == nil if it obtained a response, 89 // regardless of the response's HTTP status code. A non-nil 90 // err should be reserved for failure to obtain a response. 91 // Similarly, RoundTrip should not attempt to handle 92 // higher-level protocol details such as redirects, 93 // authentication, or cookies. 94 // 95 // RoundTrip should not modify the request, except for 96 // consuming and closing the Body, including on errors. The 97 // request's URL and Header fields are guaranteed to be 98 // initialized. 99 RoundTrip(*Request) (*Response, error) 100 } 101 102 // Given a string of the form "host", "host:port", or "[ipv6::address]:port", 103 // return true if the string includes a port. 104 func hasPort(s string) bool { return strings.LastIndex(s, ":") > strings.LastIndex(s, "]") } 105 106 // refererForURL returns a referer without any authentication info or 107 // an empty string if lastReq scheme is https and newReq scheme is http. 108 func refererForURL(lastReq, newReq *url.URL) string { 109 // https://tools.ietf.org/html/rfc7231#section-5.5.2 110 // "Clients SHOULD NOT include a Referer header field in a 111 // (non-secure) HTTP request if the referring page was 112 // transferred with a secure protocol." 113 if lastReq.Scheme == "https" && newReq.Scheme == "http" { 114 return "" 115 } 116 referer := lastReq.String() 117 if lastReq.User != nil { 118 // This is not very efficient, but is the best we can 119 // do without: 120 // - introducing a new method on URL 121 // - creating a race condition 122 // - copying the URL struct manually, which would cause 123 // maintenance problems down the line 124 auth := lastReq.User.String() + "@" 125 referer = strings.Replace(referer, auth, "", 1) 126 } 127 return referer 128 } 129 130 // Used in Send to implement io.ReadCloser by bundling together the 131 // bufio.Reader through which we read the response, and the underlying 132 // network connection. 133 type readClose struct { 134 io.Reader 135 io.Closer 136 } 137 138 func (c *Client) send(req *Request) (*Response, error) { 139 if c.Jar != nil { 140 for _, cookie := range c.Jar.Cookies(req.URL) { 141 req.AddCookie(cookie) 142 } 143 } 144 resp, err := send(req, c.transport()) 145 if err != nil { 146 return nil, err 147 } 148 if c.Jar != nil { 149 if rc := resp.Cookies(); len(rc) > 0 { 150 c.Jar.SetCookies(req.URL, rc) 151 } 152 } 153 return resp, err 154 } 155 156 // Do sends an HTTP request and returns an HTTP response, following 157 // policy (e.g. redirects, cookies, auth) as configured on the client. 158 // 159 // An error is returned if caused by client policy (such as 160 // CheckRedirect), or if there was an HTTP protocol error. 161 // A non-2xx response doesn't cause an error. 162 // 163 // When err is nil, resp always contains a non-nil resp.Body. 164 // 165 // Callers should close resp.Body when done reading from it. If 166 // resp.Body is not closed, the Client's underlying RoundTripper 167 // (typically Transport) may not be able to re-use a persistent TCP 168 // connection to the server for a subsequent "keep-alive" request. 169 // 170 // The request Body, if non-nil, will be closed by the underlying 171 // Transport, even on errors. 172 // 173 // Generally Get, Post, or PostForm will be used instead of Do. 174 func (c *Client) Do(req *Request) (resp *Response, err error) { 175 if req.Method == "" || req.Method == "GET" || req.Method == "HEAD" { 176 return c.doFollowingRedirects(req, shouldRedirectGet) 177 } 178 if req.Method == "POST" || req.Method == "PUT" { 179 return c.doFollowingRedirects(req, shouldRedirectPost) 180 } 181 return c.send(req) 182 } 183 184 func (c *Client) transport() RoundTripper { 185 if c.Transport != nil { 186 return c.Transport 187 } 188 return DefaultTransport 189 } 190 191 // send issues an HTTP request. 192 // Caller should close resp.Body when done reading from it. 193 func send(req *Request, t RoundTripper) (resp *Response, err error) { 194 if t == nil { 195 req.closeBody() 196 return nil, errors.New("http: no Client.Transport or DefaultTransport") 197 } 198 199 if req.URL == nil { 200 req.closeBody() 201 return nil, errors.New("http: nil Request.URL") 202 } 203 204 if req.RequestURI != "" { 205 req.closeBody() 206 return nil, errors.New("http: Request.RequestURI can't be set in client requests.") 207 } 208 209 // Most the callers of send (Get, Post, et al) don't need 210 // Headers, leaving it uninitialized. We guarantee to the 211 // Transport that this has been initialized, though. 212 if req.Header == nil { 213 req.Header = make(Header) 214 } 215 216 if u := req.URL.User; u != nil && req.Header.Get("Authorization") == "" { 217 username := u.Username() 218 password, _ := u.Password() 219 req.Header.Set("Authorization", "Basic "+basicAuth(username, password)) 220 } 221 resp, err = t.RoundTrip(req) 222 if err != nil { 223 if resp != nil { 224 log.Printf("RoundTripper returned a response & error; ignoring response") 225 } 226 if tlsErr, ok := err.(tls.RecordHeaderError); ok { 227 // If we get a bad TLS record header, check to see if the 228 // response looks like HTTP and give a more helpful error. 229 // See golang.org/issue/11111. 230 if string(tlsErr.RecordHeader[:]) == "HTTP/" { 231 err = errors.New("http: server gave HTTP response to HTTPS client") 232 } 233 } 234 return nil, err 235 } 236 return resp, nil 237 } 238 239 // See 2 (end of page 4) http://www.ietf.org/rfc/rfc2617.txt 240 // "To receive authorization, the client sends the userid and password, 241 // separated by a single colon (":") character, within a base64 242 // encoded string in the credentials." 243 // It is not meant to be urlencoded. 244 func basicAuth(username, password string) string { 245 auth := username + ":" + password 246 return base64.StdEncoding.EncodeToString([]byte(auth)) 247 } 248 249 // True if the specified HTTP status code is one for which the Get utility should 250 // automatically redirect. 251 func shouldRedirectGet(statusCode int) bool { 252 switch statusCode { 253 case StatusMovedPermanently, StatusFound, StatusSeeOther, StatusTemporaryRedirect: 254 return true 255 } 256 return false 257 } 258 259 // True if the specified HTTP status code is one for which the Post utility should 260 // automatically redirect. 261 func shouldRedirectPost(statusCode int) bool { 262 switch statusCode { 263 case StatusFound, StatusSeeOther: 264 return true 265 } 266 return false 267 } 268 269 // Get issues a GET to the specified URL. If the response is one of 270 // the following redirect codes, Get follows the redirect, up to a 271 // maximum of 10 redirects: 272 // 273 // 301 (Moved Permanently) 274 // 302 (Found) 275 // 303 (See Other) 276 // 307 (Temporary Redirect) 277 // 278 // An error is returned if there were too many redirects or if there 279 // was an HTTP protocol error. A non-2xx response doesn't cause an 280 // error. 281 // 282 // When err is nil, resp always contains a non-nil resp.Body. 283 // Caller should close resp.Body when done reading from it. 284 // 285 // Get is a wrapper around DefaultClient.Get. 286 // 287 // To make a request with custom headers, use NewRequest and 288 // DefaultClient.Do. 289 func Get(url string) (resp *Response, err error) { 290 return DefaultClient.Get(url) 291 } 292 293 // Get issues a GET to the specified URL. If the response is one of the 294 // following redirect codes, Get follows the redirect after calling the 295 // Client's CheckRedirect function: 296 // 297 // 301 (Moved Permanently) 298 // 302 (Found) 299 // 303 (See Other) 300 // 307 (Temporary Redirect) 301 // 302 // An error is returned if the Client's CheckRedirect function fails 303 // or if there was an HTTP protocol error. A non-2xx response doesn't 304 // cause an error. 305 // 306 // When err is nil, resp always contains a non-nil resp.Body. 307 // Caller should close resp.Body when done reading from it. 308 // 309 // To make a request with custom headers, use NewRequest and Client.Do. 310 func (c *Client) Get(url string) (resp *Response, err error) { 311 req, err := NewRequest("GET", url, nil) 312 if err != nil { 313 return nil, err 314 } 315 return c.doFollowingRedirects(req, shouldRedirectGet) 316 } 317 318 func alwaysFalse() bool { return false } 319 320 func (c *Client) doFollowingRedirects(ireq *Request, shouldRedirect func(int) bool) (resp *Response, err error) { 321 var base *url.URL 322 redirectChecker := c.CheckRedirect 323 if redirectChecker == nil { 324 redirectChecker = defaultCheckRedirect 325 } 326 var via []*Request 327 328 if ireq.URL == nil { 329 ireq.closeBody() 330 return nil, errors.New("http: nil Request.URL") 331 } 332 333 var reqmu sync.Mutex // guards req 334 req := ireq 335 336 var timer *time.Timer 337 var atomicWasCanceled int32 // atomic bool (1 or 0) 338 var wasCanceled = alwaysFalse 339 if c.Timeout > 0 { 340 wasCanceled = func() bool { return atomic.LoadInt32(&atomicWasCanceled) != 0 } 341 type canceler interface { 342 CancelRequest(*Request) 343 } 344 tr, ok := c.transport().(canceler) 345 if !ok { 346 return nil, fmt.Errorf("net/http: Client Transport of type %T doesn't support CancelRequest; Timeout not supported", c.transport()) 347 } 348 timer = time.AfterFunc(c.Timeout, func() { 349 atomic.StoreInt32(&atomicWasCanceled, 1) 350 reqmu.Lock() 351 defer reqmu.Unlock() 352 tr.CancelRequest(req) 353 }) 354 } 355 356 urlStr := "" // next relative or absolute URL to fetch (after first request) 357 redirectFailed := false 358 for redirect := 0; ; redirect++ { 359 if redirect != 0 { 360 nreq := new(Request) 361 nreq.Method = ireq.Method 362 if ireq.Method == "POST" || ireq.Method == "PUT" { 363 nreq.Method = "GET" 364 } 365 nreq.Header = make(Header) 366 nreq.URL, err = base.Parse(urlStr) 367 if err != nil { 368 break 369 } 370 if len(via) > 0 { 371 // Add the Referer header. 372 lastReq := via[len(via)-1] 373 if ref := refererForURL(lastReq.URL, nreq.URL); ref != "" { 374 nreq.Header.Set("Referer", ref) 375 } 376 377 err = redirectChecker(nreq, via) 378 if err != nil { 379 redirectFailed = true 380 break 381 } 382 } 383 reqmu.Lock() 384 req = nreq 385 reqmu.Unlock() 386 } 387 388 urlStr = req.URL.String() 389 if resp, err = c.send(req); err != nil { 390 if wasCanceled() { 391 err = &httpError{ 392 err: err.Error() + " (Client.Timeout exceeded while awaiting headers)", 393 timeout: true, 394 } 395 } 396 break 397 } 398 399 if shouldRedirect(resp.StatusCode) { 400 // Read the body if small so underlying TCP connection will be re-used. 401 // No need to check for errors: if it fails, Transport won't reuse it anyway. 402 const maxBodySlurpSize = 2 << 10 403 if resp.ContentLength == -1 || resp.ContentLength <= maxBodySlurpSize { 404 io.CopyN(ioutil.Discard, resp.Body, maxBodySlurpSize) 405 } 406 resp.Body.Close() 407 if urlStr = resp.Header.Get("Location"); urlStr == "" { 408 err = fmt.Errorf("%d response missing Location header", resp.StatusCode) 409 break 410 } 411 base = req.URL 412 via = append(via, req) 413 continue 414 } 415 if timer != nil { 416 resp.Body = &cancelTimerBody{ 417 t: timer, 418 rc: resp.Body, 419 reqWasCanceled: wasCanceled, 420 } 421 } 422 return resp, nil 423 } 424 425 method := ireq.Method 426 if method == "" { 427 method = "GET" 428 } 429 urlErr := &url.Error{ 430 Op: method[0:1] + strings.ToLower(method[1:]), 431 URL: urlStr, 432 Err: err, 433 } 434 435 if redirectFailed { 436 // Special case for Go 1 compatibility: return both the response 437 // and an error if the CheckRedirect function failed. 438 // See https://golang.org/issue/3795 439 return resp, urlErr 440 } 441 442 if resp != nil { 443 resp.Body.Close() 444 } 445 return nil, urlErr 446 } 447 448 func defaultCheckRedirect(req *Request, via []*Request) error { 449 if len(via) >= 10 { 450 return errors.New("stopped after 10 redirects") 451 } 452 return nil 453 } 454 455 // Post issues a POST to the specified URL. 456 // 457 // Caller should close resp.Body when done reading from it. 458 // 459 // If the provided body is an io.Closer, it is closed after the 460 // request. 461 // 462 // Post is a wrapper around DefaultClient.Post. 463 // 464 // To set custom headers, use NewRequest and DefaultClient.Do. 465 func Post(url string, bodyType string, body io.Reader) (resp *Response, err error) { 466 return DefaultClient.Post(url, bodyType, body) 467 } 468 469 // Post issues a POST to the specified URL. 470 // 471 // Caller should close resp.Body when done reading from it. 472 // 473 // If the provided body is an io.Closer, it is closed after the 474 // request. 475 // 476 // To set custom headers, use NewRequest and Client.Do. 477 func (c *Client) Post(url string, bodyType string, body io.Reader) (resp *Response, err error) { 478 req, err := NewRequest("POST", url, body) 479 if err != nil { 480 return nil, err 481 } 482 req.Header.Set("Content-Type", bodyType) 483 return c.doFollowingRedirects(req, shouldRedirectPost) 484 } 485 486 // PostForm issues a POST to the specified URL, with data's keys and 487 // values URL-encoded as the request body. 488 // 489 // The Content-Type header is set to application/x-www-form-urlencoded. 490 // To set other headers, use NewRequest and DefaultClient.Do. 491 // 492 // When err is nil, resp always contains a non-nil resp.Body. 493 // Caller should close resp.Body when done reading from it. 494 // 495 // PostForm is a wrapper around DefaultClient.PostForm. 496 func PostForm(url string, data url.Values) (resp *Response, err error) { 497 return DefaultClient.PostForm(url, data) 498 } 499 500 // PostForm issues a POST to the specified URL, 501 // with data's keys and values URL-encoded as the request body. 502 // 503 // The Content-Type header is set to application/x-www-form-urlencoded. 504 // To set other headers, use NewRequest and DefaultClient.Do. 505 // 506 // When err is nil, resp always contains a non-nil resp.Body. 507 // Caller should close resp.Body when done reading from it. 508 func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error) { 509 return c.Post(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode())) 510 } 511 512 // Head issues a HEAD to the specified URL. If the response is one of 513 // the following redirect codes, Head follows the redirect, up to a 514 // maximum of 10 redirects: 515 // 516 // 301 (Moved Permanently) 517 // 302 (Found) 518 // 303 (See Other) 519 // 307 (Temporary Redirect) 520 // 521 // Head is a wrapper around DefaultClient.Head 522 func Head(url string) (resp *Response, err error) { 523 return DefaultClient.Head(url) 524 } 525 526 // Head issues a HEAD to the specified URL. If the response is one of the 527 // following redirect codes, Head follows the redirect after calling the 528 // Client's CheckRedirect function: 529 // 530 // 301 (Moved Permanently) 531 // 302 (Found) 532 // 303 (See Other) 533 // 307 (Temporary Redirect) 534 func (c *Client) Head(url string) (resp *Response, err error) { 535 req, err := NewRequest("HEAD", url, nil) 536 if err != nil { 537 return nil, err 538 } 539 return c.doFollowingRedirects(req, shouldRedirectGet) 540 } 541 542 // cancelTimerBody is an io.ReadCloser that wraps rc with two features: 543 // 1) on Read EOF or Close, the timer t is Stopped, 544 // 2) On Read failure, if reqWasCanceled is true, the error is wrapped and 545 // marked as net.Error that hit its timeout. 546 type cancelTimerBody struct { 547 t *time.Timer 548 rc io.ReadCloser 549 reqWasCanceled func() bool 550 } 551 552 func (b *cancelTimerBody) Read(p []byte) (n int, err error) { 553 n, err = b.rc.Read(p) 554 if err == io.EOF { 555 b.t.Stop() 556 } else if err != nil && b.reqWasCanceled() { 557 return n, &httpError{ 558 err: err.Error() + " (Client.Timeout exceeded while reading body)", 559 timeout: true, 560 } 561 } 562 return 563 } 564 565 func (b *cancelTimerBody) Close() error { 566 err := b.rc.Close() 567 b.t.Stop() 568 return err 569 }