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