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