github.com/geraldss/go/src@v0.0.0-20210511222824-ac7d0ebfc235/net/http/request.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 Request reading and parsing. 6 7 package http 8 9 import ( 10 "bufio" 11 "bytes" 12 "context" 13 "crypto/tls" 14 "encoding/base64" 15 "errors" 16 "fmt" 17 "io" 18 "mime" 19 "mime/multipart" 20 "net" 21 "net/http/httptrace" 22 "net/textproto" 23 "net/url" 24 urlpkg "net/url" 25 "strconv" 26 "strings" 27 "sync" 28 29 "golang.org/x/net/idna" 30 ) 31 32 const ( 33 defaultMaxMemory = 32 << 20 // 32 MB 34 ) 35 36 // ErrMissingFile is returned by FormFile when the provided file field name 37 // is either not present in the request or not a file field. 38 var ErrMissingFile = errors.New("http: no such file") 39 40 // ProtocolError represents an HTTP protocol error. 41 // 42 // Deprecated: Not all errors in the http package related to protocol errors 43 // are of type ProtocolError. 44 type ProtocolError struct { 45 ErrorString string 46 } 47 48 func (pe *ProtocolError) Error() string { return pe.ErrorString } 49 50 var ( 51 // ErrNotSupported is returned by the Push method of Pusher 52 // implementations to indicate that HTTP/2 Push support is not 53 // available. 54 ErrNotSupported = &ProtocolError{"feature not supported"} 55 56 // Deprecated: ErrUnexpectedTrailer is no longer returned by 57 // anything in the net/http package. Callers should not 58 // compare errors against this variable. 59 ErrUnexpectedTrailer = &ProtocolError{"trailer header without chunked transfer encoding"} 60 61 // ErrMissingBoundary is returned by Request.MultipartReader when the 62 // request's Content-Type does not include a "boundary" parameter. 63 ErrMissingBoundary = &ProtocolError{"no multipart boundary param in Content-Type"} 64 65 // ErrNotMultipart is returned by Request.MultipartReader when the 66 // request's Content-Type is not multipart/form-data. 67 ErrNotMultipart = &ProtocolError{"request Content-Type isn't multipart/form-data"} 68 69 // Deprecated: ErrHeaderTooLong is no longer returned by 70 // anything in the net/http package. Callers should not 71 // compare errors against this variable. 72 ErrHeaderTooLong = &ProtocolError{"header too long"} 73 74 // Deprecated: ErrShortBody is no longer returned by 75 // anything in the net/http package. Callers should not 76 // compare errors against this variable. 77 ErrShortBody = &ProtocolError{"entity body too short"} 78 79 // Deprecated: ErrMissingContentLength is no longer returned by 80 // anything in the net/http package. Callers should not 81 // compare errors against this variable. 82 ErrMissingContentLength = &ProtocolError{"missing ContentLength in HEAD response"} 83 ) 84 85 func badStringError(what, val string) error { return fmt.Errorf("%s %q", what, val) } 86 87 // Headers that Request.Write handles itself and should be skipped. 88 var reqWriteExcludeHeader = map[string]bool{ 89 "Host": true, // not in Header map anyway 90 "User-Agent": true, 91 "Content-Length": true, 92 "Transfer-Encoding": true, 93 "Trailer": true, 94 } 95 96 // A Request represents an HTTP request received by a server 97 // or to be sent by a client. 98 // 99 // The field semantics differ slightly between client and server 100 // usage. In addition to the notes on the fields below, see the 101 // documentation for Request.Write and RoundTripper. 102 type Request struct { 103 // Method specifies the HTTP method (GET, POST, PUT, etc.). 104 // For client requests, an empty string means GET. 105 // 106 // Go's HTTP client does not support sending a request with 107 // the CONNECT method. See the documentation on Transport for 108 // details. 109 Method string 110 111 // URL specifies either the URI being requested (for server 112 // requests) or the URL to access (for client requests). 113 // 114 // For server requests, the URL is parsed from the URI 115 // supplied on the Request-Line as stored in RequestURI. For 116 // most requests, fields other than Path and RawQuery will be 117 // empty. (See RFC 7230, Section 5.3) 118 // 119 // For client requests, the URL's Host specifies the server to 120 // connect to, while the Request's Host field optionally 121 // specifies the Host header value to send in the HTTP 122 // request. 123 URL *url.URL 124 125 // The protocol version for incoming server requests. 126 // 127 // For client requests, these fields are ignored. The HTTP 128 // client code always uses either HTTP/1.1 or HTTP/2. 129 // See the docs on Transport for details. 130 Proto string // "HTTP/1.0" 131 ProtoMajor int // 1 132 ProtoMinor int // 0 133 134 // Header contains the request header fields either received 135 // by the server or to be sent by the client. 136 // 137 // If a server received a request with header lines, 138 // 139 // Host: example.com 140 // accept-encoding: gzip, deflate 141 // Accept-Language: en-us 142 // fOO: Bar 143 // foo: two 144 // 145 // then 146 // 147 // Header = map[string][]string{ 148 // "Accept-Encoding": {"gzip, deflate"}, 149 // "Accept-Language": {"en-us"}, 150 // "Foo": {"Bar", "two"}, 151 // } 152 // 153 // For incoming requests, the Host header is promoted to the 154 // Request.Host field and removed from the Header map. 155 // 156 // HTTP defines that header names are case-insensitive. The 157 // request parser implements this by using CanonicalHeaderKey, 158 // making the first character and any characters following a 159 // hyphen uppercase and the rest lowercase. 160 // 161 // For client requests, certain headers such as Content-Length 162 // and Connection are automatically written when needed and 163 // values in Header may be ignored. See the documentation 164 // for the Request.Write method. 165 Header Header 166 167 // Body is the request's body. 168 // 169 // For client requests, a nil body means the request has no 170 // body, such as a GET request. The HTTP Client's Transport 171 // is responsible for calling the Close method. 172 // 173 // For server requests, the Request Body is always non-nil 174 // but will return EOF immediately when no body is present. 175 // The Server will close the request body. The ServeHTTP 176 // Handler does not need to. 177 // 178 // Body must allow Read to be called concurrently with Close. 179 // In particular, calling Close should unblock a Read waiting 180 // for input. 181 Body io.ReadCloser 182 183 // GetBody defines an optional func to return a new copy of 184 // Body. It is used for client requests when a redirect requires 185 // reading the body more than once. Use of GetBody still 186 // requires setting Body. 187 // 188 // For server requests, it is unused. 189 GetBody func() (io.ReadCloser, error) 190 191 // ContentLength records the length of the associated content. 192 // The value -1 indicates that the length is unknown. 193 // Values >= 0 indicate that the given number of bytes may 194 // be read from Body. 195 // 196 // For client requests, a value of 0 with a non-nil Body is 197 // also treated as unknown. 198 ContentLength int64 199 200 // TransferEncoding lists the transfer encodings from outermost to 201 // innermost. An empty list denotes the "identity" encoding. 202 // TransferEncoding can usually be ignored; chunked encoding is 203 // automatically added and removed as necessary when sending and 204 // receiving requests. 205 TransferEncoding []string 206 207 // Close indicates whether to close the connection after 208 // replying to this request (for servers) or after sending this 209 // request and reading its response (for clients). 210 // 211 // For server requests, the HTTP server handles this automatically 212 // and this field is not needed by Handlers. 213 // 214 // For client requests, setting this field prevents re-use of 215 // TCP connections between requests to the same hosts, as if 216 // Transport.DisableKeepAlives were set. 217 Close bool 218 219 // For server requests, Host specifies the host on which the 220 // URL is sought. For HTTP/1 (per RFC 7230, section 5.4), this 221 // is either the value of the "Host" header or the host name 222 // given in the URL itself. For HTTP/2, it is the value of the 223 // ":authority" pseudo-header field. 224 // It may be of the form "host:port". For international domain 225 // names, Host may be in Punycode or Unicode form. Use 226 // golang.org/x/net/idna to convert it to either format if 227 // needed. 228 // To prevent DNS rebinding attacks, server Handlers should 229 // validate that the Host header has a value for which the 230 // Handler considers itself authoritative. The included 231 // ServeMux supports patterns registered to particular host 232 // names and thus protects its registered Handlers. 233 // 234 // For client requests, Host optionally overrides the Host 235 // header to send. If empty, the Request.Write method uses 236 // the value of URL.Host. Host may contain an international 237 // domain name. 238 Host string 239 240 // Form contains the parsed form data, including both the URL 241 // field's query parameters and the PATCH, POST, or PUT form data. 242 // This field is only available after ParseForm is called. 243 // The HTTP client ignores Form and uses Body instead. 244 Form url.Values 245 246 // PostForm contains the parsed form data from PATCH, POST 247 // or PUT body parameters. 248 // 249 // This field is only available after ParseForm is called. 250 // The HTTP client ignores PostForm and uses Body instead. 251 PostForm url.Values 252 253 // MultipartForm is the parsed multipart form, including file uploads. 254 // This field is only available after ParseMultipartForm is called. 255 // The HTTP client ignores MultipartForm and uses Body instead. 256 MultipartForm *multipart.Form 257 258 // Trailer specifies additional headers that are sent after the request 259 // body. 260 // 261 // For server requests, the Trailer map initially contains only the 262 // trailer keys, with nil values. (The client declares which trailers it 263 // will later send.) While the handler is reading from Body, it must 264 // not reference Trailer. After reading from Body returns EOF, Trailer 265 // can be read again and will contain non-nil values, if they were sent 266 // by the client. 267 // 268 // For client requests, Trailer must be initialized to a map containing 269 // the trailer keys to later send. The values may be nil or their final 270 // values. The ContentLength must be 0 or -1, to send a chunked request. 271 // After the HTTP request is sent the map values can be updated while 272 // the request body is read. Once the body returns EOF, the caller must 273 // not mutate Trailer. 274 // 275 // Few HTTP clients, servers, or proxies support HTTP trailers. 276 Trailer Header 277 278 // RemoteAddr allows HTTP servers and other software to record 279 // the network address that sent the request, usually for 280 // logging. This field is not filled in by ReadRequest and 281 // has no defined format. The HTTP server in this package 282 // sets RemoteAddr to an "IP:port" address before invoking a 283 // handler. 284 // This field is ignored by the HTTP client. 285 RemoteAddr string 286 287 // RequestURI is the unmodified request-target of the 288 // Request-Line (RFC 7230, Section 3.1.1) as sent by the client 289 // to a server. Usually the URL field should be used instead. 290 // It is an error to set this field in an HTTP client request. 291 RequestURI string 292 293 // TLS allows HTTP servers and other software to record 294 // information about the TLS connection on which the request 295 // was received. This field is not filled in by ReadRequest. 296 // The HTTP server in this package sets the field for 297 // TLS-enabled connections before invoking a handler; 298 // otherwise it leaves the field nil. 299 // This field is ignored by the HTTP client. 300 TLS *tls.ConnectionState 301 302 // Cancel is an optional channel whose closure indicates that the client 303 // request should be regarded as canceled. Not all implementations of 304 // RoundTripper may support Cancel. 305 // 306 // For server requests, this field is not applicable. 307 // 308 // Deprecated: Set the Request's context with NewRequestWithContext 309 // instead. If a Request's Cancel field and context are both 310 // set, it is undefined whether Cancel is respected. 311 Cancel <-chan struct{} 312 313 // Response is the redirect response which caused this request 314 // to be created. This field is only populated during client 315 // redirects. 316 Response *Response 317 318 // ctx is either the client or server context. It should only 319 // be modified via copying the whole Request using WithContext. 320 // It is unexported to prevent people from using Context wrong 321 // and mutating the contexts held by callers of the same request. 322 ctx context.Context 323 } 324 325 // Context returns the request's context. To change the context, use 326 // WithContext. 327 // 328 // The returned context is always non-nil; it defaults to the 329 // background context. 330 // 331 // For outgoing client requests, the context controls cancellation. 332 // 333 // For incoming server requests, the context is canceled when the 334 // client's connection closes, the request is canceled (with HTTP/2), 335 // or when the ServeHTTP method returns. 336 func (r *Request) Context() context.Context { 337 if r.ctx != nil { 338 return r.ctx 339 } 340 return context.Background() 341 } 342 343 // WithContext returns a shallow copy of r with its context changed 344 // to ctx. The provided ctx must be non-nil. 345 // 346 // For outgoing client request, the context controls the entire 347 // lifetime of a request and its response: obtaining a connection, 348 // sending the request, and reading the response headers and body. 349 // 350 // To create a new request with a context, use NewRequestWithContext. 351 // To change the context of a request, such as an incoming request you 352 // want to modify before sending back out, use Request.Clone. Between 353 // those two uses, it's rare to need WithContext. 354 func (r *Request) WithContext(ctx context.Context) *Request { 355 if ctx == nil { 356 panic("nil context") 357 } 358 r2 := new(Request) 359 *r2 = *r 360 r2.ctx = ctx 361 r2.URL = cloneURL(r.URL) // legacy behavior; TODO: try to remove. Issue 23544 362 return r2 363 } 364 365 // Clone returns a deep copy of r with its context changed to ctx. 366 // The provided ctx must be non-nil. 367 // 368 // For an outgoing client request, the context controls the entire 369 // lifetime of a request and its response: obtaining a connection, 370 // sending the request, and reading the response headers and body. 371 func (r *Request) Clone(ctx context.Context) *Request { 372 if ctx == nil { 373 panic("nil context") 374 } 375 r2 := new(Request) 376 *r2 = *r 377 r2.ctx = ctx 378 r2.URL = cloneURL(r.URL) 379 if r.Header != nil { 380 r2.Header = r.Header.Clone() 381 } 382 if r.Trailer != nil { 383 r2.Trailer = r.Trailer.Clone() 384 } 385 if s := r.TransferEncoding; s != nil { 386 s2 := make([]string, len(s)) 387 copy(s2, s) 388 r2.TransferEncoding = s2 389 } 390 r2.Form = cloneURLValues(r.Form) 391 r2.PostForm = cloneURLValues(r.PostForm) 392 r2.MultipartForm = cloneMultipartForm(r.MultipartForm) 393 return r2 394 } 395 396 // ProtoAtLeast reports whether the HTTP protocol used 397 // in the request is at least major.minor. 398 func (r *Request) ProtoAtLeast(major, minor int) bool { 399 return r.ProtoMajor > major || 400 r.ProtoMajor == major && r.ProtoMinor >= minor 401 } 402 403 // UserAgent returns the client's User-Agent, if sent in the request. 404 func (r *Request) UserAgent() string { 405 return r.Header.Get("User-Agent") 406 } 407 408 // Cookies parses and returns the HTTP cookies sent with the request. 409 func (r *Request) Cookies() []*Cookie { 410 return readCookies(r.Header, "") 411 } 412 413 // ErrNoCookie is returned by Request's Cookie method when a cookie is not found. 414 var ErrNoCookie = errors.New("http: named cookie not present") 415 416 // Cookie returns the named cookie provided in the request or 417 // ErrNoCookie if not found. 418 // If multiple cookies match the given name, only one cookie will 419 // be returned. 420 func (r *Request) Cookie(name string) (*Cookie, error) { 421 for _, c := range readCookies(r.Header, name) { 422 return c, nil 423 } 424 return nil, ErrNoCookie 425 } 426 427 // AddCookie adds a cookie to the request. Per RFC 6265 section 5.4, 428 // AddCookie does not attach more than one Cookie header field. That 429 // means all cookies, if any, are written into the same line, 430 // separated by semicolon. 431 // AddCookie only sanitizes c's name and value, and does not sanitize 432 // a Cookie header already present in the request. 433 func (r *Request) AddCookie(c *Cookie) { 434 s := fmt.Sprintf("%s=%s", sanitizeCookieName(c.Name), sanitizeCookieValue(c.Value)) 435 if c := r.Header.Get("Cookie"); c != "" { 436 r.Header.Set("Cookie", c+"; "+s) 437 } else { 438 r.Header.Set("Cookie", s) 439 } 440 } 441 442 // Referer returns the referring URL, if sent in the request. 443 // 444 // Referer is misspelled as in the request itself, a mistake from the 445 // earliest days of HTTP. This value can also be fetched from the 446 // Header map as Header["Referer"]; the benefit of making it available 447 // as a method is that the compiler can diagnose programs that use the 448 // alternate (correct English) spelling req.Referrer() but cannot 449 // diagnose programs that use Header["Referrer"]. 450 func (r *Request) Referer() string { 451 return r.Header.Get("Referer") 452 } 453 454 // multipartByReader is a sentinel value. 455 // Its presence in Request.MultipartForm indicates that parsing of the request 456 // body has been handed off to a MultipartReader instead of ParseMultipartForm. 457 var multipartByReader = &multipart.Form{ 458 Value: make(map[string][]string), 459 File: make(map[string][]*multipart.FileHeader), 460 } 461 462 // MultipartReader returns a MIME multipart reader if this is a 463 // multipart/form-data or a multipart/mixed POST request, else returns nil and an error. 464 // Use this function instead of ParseMultipartForm to 465 // process the request body as a stream. 466 func (r *Request) MultipartReader() (*multipart.Reader, error) { 467 if r.MultipartForm == multipartByReader { 468 return nil, errors.New("http: MultipartReader called twice") 469 } 470 if r.MultipartForm != nil { 471 return nil, errors.New("http: multipart handled by ParseMultipartForm") 472 } 473 r.MultipartForm = multipartByReader 474 return r.multipartReader(true) 475 } 476 477 func (r *Request) multipartReader(allowMixed bool) (*multipart.Reader, error) { 478 v := r.Header.Get("Content-Type") 479 if v == "" { 480 return nil, ErrNotMultipart 481 } 482 d, params, err := mime.ParseMediaType(v) 483 if err != nil || !(d == "multipart/form-data" || allowMixed && d == "multipart/mixed") { 484 return nil, ErrNotMultipart 485 } 486 boundary, ok := params["boundary"] 487 if !ok { 488 return nil, ErrMissingBoundary 489 } 490 return multipart.NewReader(r.Body, boundary), nil 491 } 492 493 // isH2Upgrade reports whether r represents the http2 "client preface" 494 // magic string. 495 func (r *Request) isH2Upgrade() bool { 496 return r.Method == "PRI" && len(r.Header) == 0 && r.URL.Path == "*" && r.Proto == "HTTP/2.0" 497 } 498 499 // Return value if nonempty, def otherwise. 500 func valueOrDefault(value, def string) string { 501 if value != "" { 502 return value 503 } 504 return def 505 } 506 507 // NOTE: This is not intended to reflect the actual Go version being used. 508 // It was changed at the time of Go 1.1 release because the former User-Agent 509 // had ended up blocked by some intrusion detection systems. 510 // See https://codereview.appspot.com/7532043. 511 const defaultUserAgent = "Go-http-client/1.1" 512 513 // Write writes an HTTP/1.1 request, which is the header and body, in wire format. 514 // This method consults the following fields of the request: 515 // Host 516 // URL 517 // Method (defaults to "GET") 518 // Header 519 // ContentLength 520 // TransferEncoding 521 // Body 522 // 523 // If Body is present, Content-Length is <= 0 and TransferEncoding 524 // hasn't been set to "identity", Write adds "Transfer-Encoding: 525 // chunked" to the header. Body is closed after it is sent. 526 func (r *Request) Write(w io.Writer) error { 527 return r.write(w, false, nil, nil) 528 } 529 530 // WriteProxy is like Write but writes the request in the form 531 // expected by an HTTP proxy. In particular, WriteProxy writes the 532 // initial Request-URI line of the request with an absolute URI, per 533 // section 5.3 of RFC 7230, including the scheme and host. 534 // In either case, WriteProxy also writes a Host header, using 535 // either r.Host or r.URL.Host. 536 func (r *Request) WriteProxy(w io.Writer) error { 537 return r.write(w, true, nil, nil) 538 } 539 540 // errMissingHost is returned by Write when there is no Host or URL present in 541 // the Request. 542 var errMissingHost = errors.New("http: Request.Write on Request with no Host or URL set") 543 544 // extraHeaders may be nil 545 // waitForContinue may be nil 546 // always closes body 547 func (r *Request) write(w io.Writer, usingProxy bool, extraHeaders Header, waitForContinue func() bool) (err error) { 548 trace := httptrace.ContextClientTrace(r.Context()) 549 if trace != nil && trace.WroteRequest != nil { 550 defer func() { 551 trace.WroteRequest(httptrace.WroteRequestInfo{ 552 Err: err, 553 }) 554 }() 555 } 556 closed := false 557 defer func() { 558 if closed { 559 return 560 } 561 if closeErr := r.closeBody(); closeErr != nil && err == nil { 562 err = closeErr 563 } 564 }() 565 566 // Find the target host. Prefer the Host: header, but if that 567 // is not given, use the host from the request URL. 568 // 569 // Clean the host, in case it arrives with unexpected stuff in it. 570 host := cleanHost(r.Host) 571 if host == "" { 572 if r.URL == nil { 573 return errMissingHost 574 } 575 host = cleanHost(r.URL.Host) 576 } 577 578 // According to RFC 6874, an HTTP client, proxy, or other 579 // intermediary must remove any IPv6 zone identifier attached 580 // to an outgoing URI. 581 host = removeZone(host) 582 583 ruri := r.URL.RequestURI() 584 if usingProxy && r.URL.Scheme != "" && r.URL.Opaque == "" { 585 ruri = r.URL.Scheme + "://" + host + ruri 586 } else if r.Method == "CONNECT" && r.URL.Path == "" { 587 // CONNECT requests normally give just the host and port, not a full URL. 588 ruri = host 589 if r.URL.Opaque != "" { 590 ruri = r.URL.Opaque 591 } 592 } 593 if stringContainsCTLByte(ruri) { 594 return errors.New("net/http: can't write control character in Request.URL") 595 } 596 // TODO: validate r.Method too? At least it's less likely to 597 // come from an attacker (more likely to be a constant in 598 // code). 599 600 // Wrap the writer in a bufio Writer if it's not already buffered. 601 // Don't always call NewWriter, as that forces a bytes.Buffer 602 // and other small bufio Writers to have a minimum 4k buffer 603 // size. 604 var bw *bufio.Writer 605 if _, ok := w.(io.ByteWriter); !ok { 606 bw = bufio.NewWriter(w) 607 w = bw 608 } 609 610 _, err = fmt.Fprintf(w, "%s %s HTTP/1.1\r\n", valueOrDefault(r.Method, "GET"), ruri) 611 if err != nil { 612 return err 613 } 614 615 // Header lines 616 _, err = fmt.Fprintf(w, "Host: %s\r\n", host) 617 if err != nil { 618 return err 619 } 620 if trace != nil && trace.WroteHeaderField != nil { 621 trace.WroteHeaderField("Host", []string{host}) 622 } 623 624 // Use the defaultUserAgent unless the Header contains one, which 625 // may be blank to not send the header. 626 userAgent := defaultUserAgent 627 if r.Header.has("User-Agent") { 628 userAgent = r.Header.Get("User-Agent") 629 } 630 if userAgent != "" { 631 _, err = fmt.Fprintf(w, "User-Agent: %s\r\n", userAgent) 632 if err != nil { 633 return err 634 } 635 if trace != nil && trace.WroteHeaderField != nil { 636 trace.WroteHeaderField("User-Agent", []string{userAgent}) 637 } 638 } 639 640 // Process Body,ContentLength,Close,Trailer 641 tw, err := newTransferWriter(r) 642 if err != nil { 643 return err 644 } 645 err = tw.writeHeader(w, trace) 646 if err != nil { 647 return err 648 } 649 650 err = r.Header.writeSubset(w, reqWriteExcludeHeader, trace) 651 if err != nil { 652 return err 653 } 654 655 if extraHeaders != nil { 656 err = extraHeaders.write(w, trace) 657 if err != nil { 658 return err 659 } 660 } 661 662 _, err = io.WriteString(w, "\r\n") 663 if err != nil { 664 return err 665 } 666 667 if trace != nil && trace.WroteHeaders != nil { 668 trace.WroteHeaders() 669 } 670 671 // Flush and wait for 100-continue if expected. 672 if waitForContinue != nil { 673 if bw, ok := w.(*bufio.Writer); ok { 674 err = bw.Flush() 675 if err != nil { 676 return err 677 } 678 } 679 if trace != nil && trace.Wait100Continue != nil { 680 trace.Wait100Continue() 681 } 682 if !waitForContinue() { 683 closed = true 684 r.closeBody() 685 return nil 686 } 687 } 688 689 if bw, ok := w.(*bufio.Writer); ok && tw.FlushHeaders { 690 if err := bw.Flush(); err != nil { 691 return err 692 } 693 } 694 695 // Write body and trailer 696 closed = true 697 err = tw.writeBody(w) 698 if err != nil { 699 if tw.bodyReadError == err { 700 err = requestBodyReadError{err} 701 } 702 return err 703 } 704 705 if bw != nil { 706 return bw.Flush() 707 } 708 return nil 709 } 710 711 // requestBodyReadError wraps an error from (*Request).write to indicate 712 // that the error came from a Read call on the Request.Body. 713 // This error type should not escape the net/http package to users. 714 type requestBodyReadError struct{ error } 715 716 func idnaASCII(v string) (string, error) { 717 // TODO: Consider removing this check after verifying performance is okay. 718 // Right now punycode verification, length checks, context checks, and the 719 // permissible character tests are all omitted. It also prevents the ToASCII 720 // call from salvaging an invalid IDN, when possible. As a result it may be 721 // possible to have two IDNs that appear identical to the user where the 722 // ASCII-only version causes an error downstream whereas the non-ASCII 723 // version does not. 724 // Note that for correct ASCII IDNs ToASCII will only do considerably more 725 // work, but it will not cause an allocation. 726 if isASCII(v) { 727 return v, nil 728 } 729 return idna.Lookup.ToASCII(v) 730 } 731 732 // cleanHost cleans up the host sent in request's Host header. 733 // 734 // It both strips anything after '/' or ' ', and puts the value 735 // into Punycode form, if necessary. 736 // 737 // Ideally we'd clean the Host header according to the spec: 738 // https://tools.ietf.org/html/rfc7230#section-5.4 (Host = uri-host [ ":" port ]") 739 // https://tools.ietf.org/html/rfc7230#section-2.7 (uri-host -> rfc3986's host) 740 // https://tools.ietf.org/html/rfc3986#section-3.2.2 (definition of host) 741 // But practically, what we are trying to avoid is the situation in 742 // issue 11206, where a malformed Host header used in the proxy context 743 // would create a bad request. So it is enough to just truncate at the 744 // first offending character. 745 func cleanHost(in string) string { 746 if i := strings.IndexAny(in, " /"); i != -1 { 747 in = in[:i] 748 } 749 host, port, err := net.SplitHostPort(in) 750 if err != nil { // input was just a host 751 a, err := idnaASCII(in) 752 if err != nil { 753 return in // garbage in, garbage out 754 } 755 return a 756 } 757 a, err := idnaASCII(host) 758 if err != nil { 759 return in // garbage in, garbage out 760 } 761 return net.JoinHostPort(a, port) 762 } 763 764 // removeZone removes IPv6 zone identifier from host. 765 // E.g., "[fe80::1%en0]:8080" to "[fe80::1]:8080" 766 func removeZone(host string) string { 767 if !strings.HasPrefix(host, "[") { 768 return host 769 } 770 i := strings.LastIndex(host, "]") 771 if i < 0 { 772 return host 773 } 774 j := strings.LastIndex(host[:i], "%") 775 if j < 0 { 776 return host 777 } 778 return host[:j] + host[i:] 779 } 780 781 // ParseHTTPVersion parses an HTTP version string. 782 // "HTTP/1.0" returns (1, 0, true). 783 func ParseHTTPVersion(vers string) (major, minor int, ok bool) { 784 const Big = 1000000 // arbitrary upper bound 785 switch vers { 786 case "HTTP/1.1": 787 return 1, 1, true 788 case "HTTP/1.0": 789 return 1, 0, true 790 } 791 if !strings.HasPrefix(vers, "HTTP/") { 792 return 0, 0, false 793 } 794 dot := strings.Index(vers, ".") 795 if dot < 0 { 796 return 0, 0, false 797 } 798 major, err := strconv.Atoi(vers[5:dot]) 799 if err != nil || major < 0 || major > Big { 800 return 0, 0, false 801 } 802 minor, err = strconv.Atoi(vers[dot+1:]) 803 if err != nil || minor < 0 || minor > Big { 804 return 0, 0, false 805 } 806 return major, minor, true 807 } 808 809 func validMethod(method string) bool { 810 /* 811 Method = "OPTIONS" ; Section 9.2 812 | "GET" ; Section 9.3 813 | "HEAD" ; Section 9.4 814 | "POST" ; Section 9.5 815 | "PUT" ; Section 9.6 816 | "DELETE" ; Section 9.7 817 | "TRACE" ; Section 9.8 818 | "CONNECT" ; Section 9.9 819 | extension-method 820 extension-method = token 821 token = 1*<any CHAR except CTLs or separators> 822 */ 823 return len(method) > 0 && strings.IndexFunc(method, isNotToken) == -1 824 } 825 826 // NewRequest wraps NewRequestWithContext using the background context. 827 func NewRequest(method, url string, body io.Reader) (*Request, error) { 828 return NewRequestWithContext(context.Background(), method, url, body) 829 } 830 831 // NewRequestWithContext returns a new Request given a method, URL, and 832 // optional body. 833 // 834 // If the provided body is also an io.Closer, the returned 835 // Request.Body is set to body and will be closed by the Client 836 // methods Do, Post, and PostForm, and Transport.RoundTrip. 837 // 838 // NewRequestWithContext returns a Request suitable for use with 839 // Client.Do or Transport.RoundTrip. To create a request for use with 840 // testing a Server Handler, either use the NewRequest function in the 841 // net/http/httptest package, use ReadRequest, or manually update the 842 // Request fields. For an outgoing client request, the context 843 // controls the entire lifetime of a request and its response: 844 // obtaining a connection, sending the request, and reading the 845 // response headers and body. See the Request type's documentation for 846 // the difference between inbound and outbound request fields. 847 // 848 // If body is of type *bytes.Buffer, *bytes.Reader, or 849 // *strings.Reader, the returned request's ContentLength is set to its 850 // exact value (instead of -1), GetBody is populated (so 307 and 308 851 // redirects can replay the body), and Body is set to NoBody if the 852 // ContentLength is 0. 853 func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error) { 854 if method == "" { 855 // We document that "" means "GET" for Request.Method, and people have 856 // relied on that from NewRequest, so keep that working. 857 // We still enforce validMethod for non-empty methods. 858 method = "GET" 859 } 860 if !validMethod(method) { 861 return nil, fmt.Errorf("net/http: invalid method %q", method) 862 } 863 if ctx == nil { 864 return nil, errors.New("net/http: nil Context") 865 } 866 u, err := urlpkg.Parse(url) 867 if err != nil { 868 return nil, err 869 } 870 rc, ok := body.(io.ReadCloser) 871 if !ok && body != nil { 872 rc = io.NopCloser(body) 873 } 874 // The host's colon:port should be normalized. See Issue 14836. 875 u.Host = removeEmptyPort(u.Host) 876 req := &Request{ 877 ctx: ctx, 878 Method: method, 879 URL: u, 880 Proto: "HTTP/1.1", 881 ProtoMajor: 1, 882 ProtoMinor: 1, 883 Header: make(Header), 884 Body: rc, 885 Host: u.Host, 886 } 887 if body != nil { 888 switch v := body.(type) { 889 case *bytes.Buffer: 890 req.ContentLength = int64(v.Len()) 891 buf := v.Bytes() 892 req.GetBody = func() (io.ReadCloser, error) { 893 r := bytes.NewReader(buf) 894 return io.NopCloser(r), nil 895 } 896 case *bytes.Reader: 897 req.ContentLength = int64(v.Len()) 898 snapshot := *v 899 req.GetBody = func() (io.ReadCloser, error) { 900 r := snapshot 901 return io.NopCloser(&r), nil 902 } 903 case *strings.Reader: 904 req.ContentLength = int64(v.Len()) 905 snapshot := *v 906 req.GetBody = func() (io.ReadCloser, error) { 907 r := snapshot 908 return io.NopCloser(&r), nil 909 } 910 default: 911 // This is where we'd set it to -1 (at least 912 // if body != NoBody) to mean unknown, but 913 // that broke people during the Go 1.8 testing 914 // period. People depend on it being 0 I 915 // guess. Maybe retry later. See Issue 18117. 916 } 917 // For client requests, Request.ContentLength of 0 918 // means either actually 0, or unknown. The only way 919 // to explicitly say that the ContentLength is zero is 920 // to set the Body to nil. But turns out too much code 921 // depends on NewRequest returning a non-nil Body, 922 // so we use a well-known ReadCloser variable instead 923 // and have the http package also treat that sentinel 924 // variable to mean explicitly zero. 925 if req.GetBody != nil && req.ContentLength == 0 { 926 req.Body = NoBody 927 req.GetBody = func() (io.ReadCloser, error) { return NoBody, nil } 928 } 929 } 930 931 return req, nil 932 } 933 934 // BasicAuth returns the username and password provided in the request's 935 // Authorization header, if the request uses HTTP Basic Authentication. 936 // See RFC 2617, Section 2. 937 func (r *Request) BasicAuth() (username, password string, ok bool) { 938 auth := r.Header.Get("Authorization") 939 if auth == "" { 940 return 941 } 942 return parseBasicAuth(auth) 943 } 944 945 // parseBasicAuth parses an HTTP Basic Authentication string. 946 // "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" returns ("Aladdin", "open sesame", true). 947 func parseBasicAuth(auth string) (username, password string, ok bool) { 948 const prefix = "Basic " 949 // Case insensitive prefix match. See Issue 22736. 950 if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) { 951 return 952 } 953 c, err := base64.StdEncoding.DecodeString(auth[len(prefix):]) 954 if err != nil { 955 return 956 } 957 cs := string(c) 958 s := strings.IndexByte(cs, ':') 959 if s < 0 { 960 return 961 } 962 return cs[:s], cs[s+1:], true 963 } 964 965 // SetBasicAuth sets the request's Authorization header to use HTTP 966 // Basic Authentication with the provided username and password. 967 // 968 // With HTTP Basic Authentication the provided username and password 969 // are not encrypted. 970 // 971 // Some protocols may impose additional requirements on pre-escaping the 972 // username and password. For instance, when used with OAuth2, both arguments 973 // must be URL encoded first with url.QueryEscape. 974 func (r *Request) SetBasicAuth(username, password string) { 975 r.Header.Set("Authorization", "Basic "+basicAuth(username, password)) 976 } 977 978 // parseRequestLine parses "GET /foo HTTP/1.1" into its three parts. 979 func parseRequestLine(line string) (method, requestURI, proto string, ok bool) { 980 s1 := strings.Index(line, " ") 981 s2 := strings.Index(line[s1+1:], " ") 982 if s1 < 0 || s2 < 0 { 983 return 984 } 985 s2 += s1 + 1 986 return line[:s1], line[s1+1 : s2], line[s2+1:], true 987 } 988 989 var textprotoReaderPool sync.Pool 990 991 func newTextprotoReader(br *bufio.Reader) *textproto.Reader { 992 if v := textprotoReaderPool.Get(); v != nil { 993 tr := v.(*textproto.Reader) 994 tr.R = br 995 return tr 996 } 997 return textproto.NewReader(br) 998 } 999 1000 func putTextprotoReader(r *textproto.Reader) { 1001 r.R = nil 1002 textprotoReaderPool.Put(r) 1003 } 1004 1005 // ReadRequest reads and parses an incoming request from b. 1006 // 1007 // ReadRequest is a low-level function and should only be used for 1008 // specialized applications; most code should use the Server to read 1009 // requests and handle them via the Handler interface. ReadRequest 1010 // only supports HTTP/1.x requests. For HTTP/2, use golang.org/x/net/http2. 1011 func ReadRequest(b *bufio.Reader) (*Request, error) { 1012 return readRequest(b, deleteHostHeader) 1013 } 1014 1015 // Constants for readRequest's deleteHostHeader parameter. 1016 const ( 1017 deleteHostHeader = true 1018 keepHostHeader = false 1019 ) 1020 1021 func readRequest(b *bufio.Reader, deleteHostHeader bool) (req *Request, err error) { 1022 tp := newTextprotoReader(b) 1023 req = new(Request) 1024 1025 // First line: GET /index.html HTTP/1.0 1026 var s string 1027 if s, err = tp.ReadLine(); err != nil { 1028 return nil, err 1029 } 1030 defer func() { 1031 putTextprotoReader(tp) 1032 if err == io.EOF { 1033 err = io.ErrUnexpectedEOF 1034 } 1035 }() 1036 1037 var ok bool 1038 req.Method, req.RequestURI, req.Proto, ok = parseRequestLine(s) 1039 if !ok { 1040 return nil, badStringError("malformed HTTP request", s) 1041 } 1042 if !validMethod(req.Method) { 1043 return nil, badStringError("invalid method", req.Method) 1044 } 1045 rawurl := req.RequestURI 1046 if req.ProtoMajor, req.ProtoMinor, ok = ParseHTTPVersion(req.Proto); !ok { 1047 return nil, badStringError("malformed HTTP version", req.Proto) 1048 } 1049 1050 // CONNECT requests are used two different ways, and neither uses a full URL: 1051 // The standard use is to tunnel HTTPS through an HTTP proxy. 1052 // It looks like "CONNECT www.google.com:443 HTTP/1.1", and the parameter is 1053 // just the authority section of a URL. This information should go in req.URL.Host. 1054 // 1055 // The net/rpc package also uses CONNECT, but there the parameter is a path 1056 // that starts with a slash. It can be parsed with the regular URL parser, 1057 // and the path will end up in req.URL.Path, where it needs to be in order for 1058 // RPC to work. 1059 justAuthority := req.Method == "CONNECT" && !strings.HasPrefix(rawurl, "/") 1060 if justAuthority { 1061 rawurl = "http://" + rawurl 1062 } 1063 1064 if req.URL, err = url.ParseRequestURI(rawurl); err != nil { 1065 return nil, err 1066 } 1067 1068 if justAuthority { 1069 // Strip the bogus "http://" back off. 1070 req.URL.Scheme = "" 1071 } 1072 1073 // Subsequent lines: Key: value. 1074 mimeHeader, err := tp.ReadMIMEHeader() 1075 if err != nil { 1076 return nil, err 1077 } 1078 req.Header = Header(mimeHeader) 1079 1080 // RFC 7230, section 5.3: Must treat 1081 // GET /index.html HTTP/1.1 1082 // Host: www.google.com 1083 // and 1084 // GET http://www.google.com/index.html HTTP/1.1 1085 // Host: doesntmatter 1086 // the same. In the second case, any Host line is ignored. 1087 req.Host = req.URL.Host 1088 if req.Host == "" { 1089 req.Host = req.Header.get("Host") 1090 } 1091 if deleteHostHeader { 1092 delete(req.Header, "Host") 1093 } 1094 1095 fixPragmaCacheControl(req.Header) 1096 1097 req.Close = shouldClose(req.ProtoMajor, req.ProtoMinor, req.Header, false) 1098 1099 err = readTransfer(req, b) 1100 if err != nil { 1101 return nil, err 1102 } 1103 1104 if req.isH2Upgrade() { 1105 // Because it's neither chunked, nor declared: 1106 req.ContentLength = -1 1107 1108 // We want to give handlers a chance to hijack the 1109 // connection, but we need to prevent the Server from 1110 // dealing with the connection further if it's not 1111 // hijacked. Set Close to ensure that: 1112 req.Close = true 1113 } 1114 return req, nil 1115 } 1116 1117 // MaxBytesReader is similar to io.LimitReader but is intended for 1118 // limiting the size of incoming request bodies. In contrast to 1119 // io.LimitReader, MaxBytesReader's result is a ReadCloser, returns a 1120 // non-EOF error for a Read beyond the limit, and closes the 1121 // underlying reader when its Close method is called. 1122 // 1123 // MaxBytesReader prevents clients from accidentally or maliciously 1124 // sending a large request and wasting server resources. 1125 func MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser { 1126 return &maxBytesReader{w: w, r: r, n: n} 1127 } 1128 1129 type maxBytesReader struct { 1130 w ResponseWriter 1131 r io.ReadCloser // underlying reader 1132 n int64 // max bytes remaining 1133 err error // sticky error 1134 } 1135 1136 func (l *maxBytesReader) Read(p []byte) (n int, err error) { 1137 if l.err != nil { 1138 return 0, l.err 1139 } 1140 if len(p) == 0 { 1141 return 0, nil 1142 } 1143 // If they asked for a 32KB byte read but only 5 bytes are 1144 // remaining, no need to read 32KB. 6 bytes will answer the 1145 // question of the whether we hit the limit or go past it. 1146 if int64(len(p)) > l.n+1 { 1147 p = p[:l.n+1] 1148 } 1149 n, err = l.r.Read(p) 1150 1151 if int64(n) <= l.n { 1152 l.n -= int64(n) 1153 l.err = err 1154 return n, err 1155 } 1156 1157 n = int(l.n) 1158 l.n = 0 1159 1160 // The server code and client code both use 1161 // maxBytesReader. This "requestTooLarge" check is 1162 // only used by the server code. To prevent binaries 1163 // which only using the HTTP Client code (such as 1164 // cmd/go) from also linking in the HTTP server, don't 1165 // use a static type assertion to the server 1166 // "*response" type. Check this interface instead: 1167 type requestTooLarger interface { 1168 requestTooLarge() 1169 } 1170 if res, ok := l.w.(requestTooLarger); ok { 1171 res.requestTooLarge() 1172 } 1173 l.err = errors.New("http: request body too large") 1174 return n, l.err 1175 } 1176 1177 func (l *maxBytesReader) Close() error { 1178 return l.r.Close() 1179 } 1180 1181 func copyValues(dst, src url.Values) { 1182 for k, vs := range src { 1183 dst[k] = append(dst[k], vs...) 1184 } 1185 } 1186 1187 func parsePostForm(r *Request) (vs url.Values, err error) { 1188 if r.Body == nil { 1189 err = errors.New("missing form body") 1190 return 1191 } 1192 ct := r.Header.Get("Content-Type") 1193 // RFC 7231, section 3.1.1.5 - empty type 1194 // MAY be treated as application/octet-stream 1195 if ct == "" { 1196 ct = "application/octet-stream" 1197 } 1198 ct, _, err = mime.ParseMediaType(ct) 1199 switch { 1200 case ct == "application/x-www-form-urlencoded": 1201 var reader io.Reader = r.Body 1202 maxFormSize := int64(1<<63 - 1) 1203 if _, ok := r.Body.(*maxBytesReader); !ok { 1204 maxFormSize = int64(10 << 20) // 10 MB is a lot of text. 1205 reader = io.LimitReader(r.Body, maxFormSize+1) 1206 } 1207 b, e := io.ReadAll(reader) 1208 if e != nil { 1209 if err == nil { 1210 err = e 1211 } 1212 break 1213 } 1214 if int64(len(b)) > maxFormSize { 1215 err = errors.New("http: POST too large") 1216 return 1217 } 1218 vs, e = url.ParseQuery(string(b)) 1219 if err == nil { 1220 err = e 1221 } 1222 case ct == "multipart/form-data": 1223 // handled by ParseMultipartForm (which is calling us, or should be) 1224 // TODO(bradfitz): there are too many possible 1225 // orders to call too many functions here. 1226 // Clean this up and write more tests. 1227 // request_test.go contains the start of this, 1228 // in TestParseMultipartFormOrder and others. 1229 } 1230 return 1231 } 1232 1233 // ParseForm populates r.Form and r.PostForm. 1234 // 1235 // For all requests, ParseForm parses the raw query from the URL and updates 1236 // r.Form. 1237 // 1238 // For POST, PUT, and PATCH requests, it also reads the request body, parses it 1239 // as a form and puts the results into both r.PostForm and r.Form. Request body 1240 // parameters take precedence over URL query string values in r.Form. 1241 // 1242 // If the request Body's size has not already been limited by MaxBytesReader, 1243 // the size is capped at 10MB. 1244 // 1245 // For other HTTP methods, or when the Content-Type is not 1246 // application/x-www-form-urlencoded, the request Body is not read, and 1247 // r.PostForm is initialized to a non-nil, empty value. 1248 // 1249 // ParseMultipartForm calls ParseForm automatically. 1250 // ParseForm is idempotent. 1251 func (r *Request) ParseForm() error { 1252 var err error 1253 if r.PostForm == nil { 1254 if r.Method == "POST" || r.Method == "PUT" || r.Method == "PATCH" { 1255 r.PostForm, err = parsePostForm(r) 1256 } 1257 if r.PostForm == nil { 1258 r.PostForm = make(url.Values) 1259 } 1260 } 1261 if r.Form == nil { 1262 if len(r.PostForm) > 0 { 1263 r.Form = make(url.Values) 1264 copyValues(r.Form, r.PostForm) 1265 } 1266 var newValues url.Values 1267 if r.URL != nil { 1268 var e error 1269 newValues, e = url.ParseQuery(r.URL.RawQuery) 1270 if err == nil { 1271 err = e 1272 } 1273 } 1274 if newValues == nil { 1275 newValues = make(url.Values) 1276 } 1277 if r.Form == nil { 1278 r.Form = newValues 1279 } else { 1280 copyValues(r.Form, newValues) 1281 } 1282 } 1283 return err 1284 } 1285 1286 // ParseMultipartForm parses a request body as multipart/form-data. 1287 // The whole request body is parsed and up to a total of maxMemory bytes of 1288 // its file parts are stored in memory, with the remainder stored on 1289 // disk in temporary files. 1290 // ParseMultipartForm calls ParseForm if necessary. 1291 // After one call to ParseMultipartForm, subsequent calls have no effect. 1292 func (r *Request) ParseMultipartForm(maxMemory int64) error { 1293 if r.MultipartForm == multipartByReader { 1294 return errors.New("http: multipart handled by MultipartReader") 1295 } 1296 if r.Form == nil { 1297 err := r.ParseForm() 1298 if err != nil { 1299 return err 1300 } 1301 } 1302 if r.MultipartForm != nil { 1303 return nil 1304 } 1305 1306 mr, err := r.multipartReader(false) 1307 if err != nil { 1308 return err 1309 } 1310 1311 f, err := mr.ReadForm(maxMemory) 1312 if err != nil { 1313 return err 1314 } 1315 1316 if r.PostForm == nil { 1317 r.PostForm = make(url.Values) 1318 } 1319 for k, v := range f.Value { 1320 r.Form[k] = append(r.Form[k], v...) 1321 // r.PostForm should also be populated. See Issue 9305. 1322 r.PostForm[k] = append(r.PostForm[k], v...) 1323 } 1324 1325 r.MultipartForm = f 1326 1327 return nil 1328 } 1329 1330 // FormValue returns the first value for the named component of the query. 1331 // POST and PUT body parameters take precedence over URL query string values. 1332 // FormValue calls ParseMultipartForm and ParseForm if necessary and ignores 1333 // any errors returned by these functions. 1334 // If key is not present, FormValue returns the empty string. 1335 // To access multiple values of the same key, call ParseForm and 1336 // then inspect Request.Form directly. 1337 func (r *Request) FormValue(key string) string { 1338 if r.Form == nil { 1339 r.ParseMultipartForm(defaultMaxMemory) 1340 } 1341 if vs := r.Form[key]; len(vs) > 0 { 1342 return vs[0] 1343 } 1344 return "" 1345 } 1346 1347 // PostFormValue returns the first value for the named component of the POST, 1348 // PATCH, or PUT request body. URL query parameters are ignored. 1349 // PostFormValue calls ParseMultipartForm and ParseForm if necessary and ignores 1350 // any errors returned by these functions. 1351 // If key is not present, PostFormValue returns the empty string. 1352 func (r *Request) PostFormValue(key string) string { 1353 if r.PostForm == nil { 1354 r.ParseMultipartForm(defaultMaxMemory) 1355 } 1356 if vs := r.PostForm[key]; len(vs) > 0 { 1357 return vs[0] 1358 } 1359 return "" 1360 } 1361 1362 // FormFile returns the first file for the provided form key. 1363 // FormFile calls ParseMultipartForm and ParseForm if necessary. 1364 func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error) { 1365 if r.MultipartForm == multipartByReader { 1366 return nil, nil, errors.New("http: multipart handled by MultipartReader") 1367 } 1368 if r.MultipartForm == nil { 1369 err := r.ParseMultipartForm(defaultMaxMemory) 1370 if err != nil { 1371 return nil, nil, err 1372 } 1373 } 1374 if r.MultipartForm != nil && r.MultipartForm.File != nil { 1375 if fhs := r.MultipartForm.File[key]; len(fhs) > 0 { 1376 f, err := fhs[0].Open() 1377 return f, fhs[0], err 1378 } 1379 } 1380 return nil, nil, ErrMissingFile 1381 } 1382 1383 func (r *Request) expectsContinue() bool { 1384 return hasToken(r.Header.get("Expect"), "100-continue") 1385 } 1386 1387 func (r *Request) wantsHttp10KeepAlive() bool { 1388 if r.ProtoMajor != 1 || r.ProtoMinor != 0 { 1389 return false 1390 } 1391 return hasToken(r.Header.get("Connection"), "keep-alive") 1392 } 1393 1394 func (r *Request) wantsClose() bool { 1395 if r.Close { 1396 return true 1397 } 1398 return hasToken(r.Header.get("Connection"), "close") 1399 } 1400 1401 func (r *Request) closeBody() error { 1402 if r.Body == nil { 1403 return nil 1404 } 1405 return r.Body.Close() 1406 } 1407 1408 func (r *Request) isReplayable() bool { 1409 if r.Body == nil || r.Body == NoBody || r.GetBody != nil { 1410 switch valueOrDefault(r.Method, "GET") { 1411 case "GET", "HEAD", "OPTIONS", "TRACE": 1412 return true 1413 } 1414 // The Idempotency-Key, while non-standard, is widely used to 1415 // mean a POST or other request is idempotent. See 1416 // https://golang.org/issue/19943#issuecomment-421092421 1417 if r.Header.has("Idempotency-Key") || r.Header.has("X-Idempotency-Key") { 1418 return true 1419 } 1420 } 1421 return false 1422 } 1423 1424 // outgoingLength reports the Content-Length of this outgoing (Client) request. 1425 // It maps 0 into -1 (unknown) when the Body is non-nil. 1426 func (r *Request) outgoingLength() int64 { 1427 if r.Body == nil || r.Body == NoBody { 1428 return 0 1429 } 1430 if r.ContentLength != 0 { 1431 return r.ContentLength 1432 } 1433 return -1 1434 } 1435 1436 // requestMethodUsuallyLacksBody reports whether the given request 1437 // method is one that typically does not involve a request body. 1438 // This is used by the Transport (via 1439 // transferWriter.shouldSendChunkedRequestBody) to determine whether 1440 // we try to test-read a byte from a non-nil Request.Body when 1441 // Request.outgoingLength() returns -1. See the comments in 1442 // shouldSendChunkedRequestBody. 1443 func requestMethodUsuallyLacksBody(method string) bool { 1444 switch method { 1445 case "GET", "HEAD", "DELETE", "OPTIONS", "PROPFIND", "SEARCH": 1446 return true 1447 } 1448 return false 1449 } 1450 1451 // requiresHTTP1 reports whether this request requires being sent on 1452 // an HTTP/1 connection. 1453 func (r *Request) requiresHTTP1() bool { 1454 return hasToken(r.Header.Get("Connection"), "upgrade") && 1455 strings.EqualFold(r.Header.Get("Upgrade"), "websocket") 1456 }