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