github.com/hikaru7719/go@v0.0.0-20181025140707-c8b2ac68906a/src/net/http/request.go (about)

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