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