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