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