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