github.com/mtsmfm/go/src@v0.0.0-20221020090648-44bdcb9f8fde/net/http/request.go (about)

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