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