net/http
Index
- func Handle(pattern string, handler Handler)
- func HandleFunc(pattern string, handler func(ResponseWriter, *Request))
- func ListenAndServe(addr string, handler Handler) error
- func NewRequest(method, url string, body io.Reader) (*Request, error)
- func PostForm(url string, data url.Values) (resp *Response, err error)
- func Serve(l net.Listener, handler Handler) error
- func SetCookie(w ResponseWriter, cookie *Cookie)
- func NewServeMux() *ServeMux
- type Client
- func (c *Client) CloseIdleConnections()
- func (c *Client) Do(req *Request) (*Response, error)
- func (c *Client) Get(url string) (resp *Response, err error)
- func (c *Client) Head(url string) (resp *Response, err error)
- func (c *Client) Post(url, contentType string, body io.Reader) (resp *Response, err error)
- func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error)
- type CloseNotifier
- type Cookie
- type CookieJar
- type File
- type FileSystem
- type Flusher
- type Handler
- type Hijacker
- type Pusher
- type Request
- func (r *Request) AddCookie(c *Cookie)
- func (r *Request) BasicAuth() (username, password string, ok bool)
- func (r *Request) Clone(ctx context.Context) *Request
- func (r *Request) Context() context.Context
- func (r *Request) Cookie(name string) (*Cookie, error)
- func (r *Request) Cookies() []*Cookie
- func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error)
- func (r *Request) FormValue(key string) string
- func (r *Request) MultipartReader() (*multipart.Reader, error)
- func (r *Request) ParseForm() error
- func (r *Request) ParseMultipartForm(maxMemory int64) error
- func (r *Request) PostFormValue(key string) string
- func (r *Request) ProtoAtLeast(major, minor int) bool
- func (r *Request) Referer() string
- func (r *Request) SetBasicAuth(username, password string)
- func (r *Request) UserAgent() string
- func (r *Request) WithContext(ctx context.Context) *Request
- func (r *Request) Write(w io.Writer) error
- func (r *Request) WriteProxy(w io.Writer) error
- type Response
- func (r *Response) Cookies() []*Cookie
- func (r *Response) Location() (*url.URL, error)
- func (r *Response) ProtoAtLeast(major, minor int) bool
- func (r *Response) Write(w io.Writer) error
- type ResponseWriter
- type RoundTripper
- type ServeMux
- func NewServeMux() *ServeMux
- func (mux *ServeMux) Handle(pattern string, handler Handler)
- func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))
- func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string)
- func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request)
Functions
func Handle
1func Handle(pattern string, handler Handler)
Handle registers the handler for the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched.
1// Copyright 2018 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
5package http_test
6
7import (
8"fmt"
9"log"
10"net/http"
11"sync"
12)
13
14type countHandler struct {
15mu sync.Mutex // guards n
16n int
17}
18
19func (h *countHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
20h.mu.Lock()
21defer h.mu.Unlock()
22h.n++
23fmt.Fprintf(w, "count is %d\n", h.n)
24}
25
26func ExampleHandle() {
27http.Handle("/count", new(countHandler))
28log.Fatal(http.ListenAndServe(":8080", nil))
29}
func HandleFunc
1func HandleFunc(pattern string, handler func(ResponseWriter, *Request))
HandleFunc registers the handler function for the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched.
1h1 := func(w http.ResponseWriter, _ *http.Request) {
2 io.WriteString(w, "Hello from a HandleFunc #1!\n")
3}
4h2 := func(w http.ResponseWriter, _ *http.Request) {
5 io.WriteString(w, "Hello from a HandleFunc #2!\n")
6}
7
8http.HandleFunc("/", h1)
9http.HandleFunc("/endpoint", h2)
10
11log.Fatal(http.ListenAndServe(":8080", nil))
func ListenAndServe
1func ListenAndServe(addr string, handler Handler) error
ListenAndServe listens on the TCP network address addr and then calls Serve with handler to handle requests on incoming connections. Accepted connections are configured to enable TCP keep-alives.
The handler is typically nil, in which case the DefaultServeMux is used.
ListenAndServe always returns a non-nil error.
1helloHandler := func(w http.ResponseWriter, req *http.Request) {
2 io.WriteString(w, "Hello, world!\n")
3}
4
5http.HandleFunc("/hello", helloHandler)
6log.Fatal(http.ListenAndServe(":8080", nil))
func NewRequest
1func NewRequest(method, url string, body io.Reader) (*Request, error)
NewRequest wraps NewRequestWithContext using context.Background.
func PostForm
1func PostForm(url string, data url.Values) (resp *Response, err error)
PostForm issues a POST to the specified URL, with data's keys and values URL-encoded as the request body.
The Content-Type header is set to application/x-www-form-urlencoded. To set other headers, use NewRequest and DefaultClient.Do.
When err is nil, resp always contains a non-nil resp.Body. Caller should close resp.Body when done reading from it.
PostForm is a wrapper around DefaultClient.PostForm.
See the Client.Do method documentation for details on how redirects are handled.
To make a request with a specified context.Context, use NewRequestWithContext and DefaultClient.Do.
func Serve
1func Serve(l net.Listener, handler Handler) error
Serve accepts incoming HTTP connections on the listener l, creating a new service goroutine for each. The service goroutines read requests and then call handler to reply to them.
The handler is typically nil, in which case the DefaultServeMux is used.
HTTP/2 support is only enabled if the Listener returns *tls.Conn connections and they were configured with “h2” in the TLS Config.NextProtos.
Serve always returns a non-nil error.
func SetCookie
1func SetCookie(w ResponseWriter, cookie *Cookie)
SetCookie adds a Set-Cookie header to the provided ResponseWriter's headers. The provided cookie must have a valid Name. Invalid cookies may be silently dropped.
Types
type Client
1type Client struct {
2 // Transport specifies the mechanism by which individual
3 // HTTP requests are made.
4 // If nil, DefaultTransport is used.
5 Transport RoundTripper
6
7 // CheckRedirect specifies the policy for handling redirects.
8 // If CheckRedirect is not nil, the client calls it before
9 // following an HTTP redirect. The arguments req and via are
10 // the upcoming request and the requests made already, oldest
11 // first. If CheckRedirect returns an error, the Client's Get
12 // method returns both the previous Response (with its Body
13 // closed) and CheckRedirect's error (wrapped in a url.Error)
14 // instead of issuing the Request req.
15 // As a special case, if CheckRedirect returns ErrUseLastResponse,
16 // then the most recent response is returned with its body
17 // unclosed, along with a nil error.
18 //
19 // If CheckRedirect is nil, the Client uses its default policy,
20 // which is to stop after 10 consecutive requests.
21 CheckRedirect func(req *Request, via []*Request) error
22
23 // Jar specifies the cookie jar.
24 //
25 // The Jar is used to insert relevant cookies into every
26 // outbound Request and is updated with the cookie values
27 // of every inbound Response. The Jar is consulted for every
28 // redirect that the Client follows.
29 //
30 // If Jar is nil, cookies are only sent if they are explicitly
31 // set on the Request.
32 Jar CookieJar
33
34 // Timeout specifies a time limit for requests made by this
35 // Client. The timeout includes connection time, any
36 // redirects, and reading the response body. The timer remains
37 // running after Get, Head, Post, or Do return and will
38 // interrupt reading of the Response.Body.
39 //
40 // A Timeout of zero means no timeout.
41 //
42 // The Client cancels requests to the underlying Transport
43 // as if the Request's Context ended.
44 //
45 // For compatibility, the Client will also use the deprecated
46 // CancelRequest method on Transport if found. New
47 // RoundTripper implementations should use the Request's Context
48 // for cancellation instead of implementing CancelRequest.
49 Timeout time.Duration
50}
A Client is an HTTP client. Its zero value (DefaultClient) is a usable client that uses DefaultTransport.
The Client’s Transport typically has internal state (cached TCP connections), so Clients should be reused instead of created as needed. Clients are safe for concurrent use by multiple goroutines.
A Client is higher-level than a RoundTripper (such as Transport) and additionally handles HTTP details such as cookies and redirects.
When following redirects, the Client will forward all headers set on the initial Request except:
• when forwarding sensitive headers like “Authorization”, “WWW-Authenticate”, and “Cookie” to untrusted targets. These headers will be ignored when following a redirect to a domain that is not a subdomain match or exact match of the initial domain. For example, a redirect from “foo.com” to either “foo.com” or “sub.foo.com” will forward the sensitive headers, but a redirect to “bar.com” will not.
• when forwarding the “Cookie” header with a non-nil cookie Jar. Since each redirect may mutate the state of the cookie jar, a redirect may possibly alter a cookie set in the initial request. When forwarding the “Cookie” header, any mutated cookies will be omitted, with the expectation that the Jar will insert those mutated cookies with the updated values (assuming the origin matches). If Jar is nil, the initial cookies are forwarded without change.
func CloseIdleConnections
1func (c *Client) CloseIdleConnections()
CloseIdleConnections closes any connections on its Transport which were previously connected from previous requests but are now sitting idle in a "keep-alive" state. It does not interrupt any connections currently in use.
If the Client’s Transport does not have a CloseIdleConnections method then this method does nothing.
func Do
1func (c *Client) Do(req *Request) (*Response, error)
Do sends an HTTP request and returns an HTTP response, following policy (such as redirects, cookies, auth) as configured on the client.
An error is returned if caused by client policy (such as CheckRedirect), or failure to speak HTTP (such as a network connectivity problem). A non-2xx status code doesn’t cause an error.
If the returned error is nil, the Response will contain a non-nil Body which the user is expected to close. If the Body is not both read to EOF and closed, the Client’s underlying RoundTripper (typically Transport) may not be able to re-use a persistent TCP connection to the server for a subsequent “keep-alive” request.
The request Body, if non-nil, will be closed by the underlying Transport, even on errors.
On error, any Response can be ignored. A non-nil Response with a non-nil error only occurs when CheckRedirect fails, and even then the returned Response.Body is already closed.
Generally Get, Post, or PostForm will be used instead of Do.
If the server replies with a redirect, the Client first uses the CheckRedirect function to determine whether the redirect should be followed. If permitted, a 301, 302, or 303 redirect causes subsequent requests to use HTTP method GET (or HEAD if the original request was HEAD), with no body. A 307 or 308 redirect preserves the original HTTP method and body, provided that the Request.GetBody function is defined. The NewRequest function automatically sets GetBody for common standard library body types.
Any returned error will be of type *url.Error. The url.Error value’s Timeout method will report true if the request timed out.
func Get
1func (c *Client) Get(url string) (resp *Response, err error)
Get issues a GET to the specified URL. If the response is one of the following redirect codes, Get follows the redirect after calling the Client's CheckRedirect function:
301 (Moved Permanently)
302 (Found)
303 (See Other)
307 (Temporary Redirect)
308 (Permanent Redirect)
An error is returned if the Client’s CheckRedirect function fails or if there was an HTTP protocol error. A non-2xx response doesn’t cause an error. Any returned error will be of type *url.Error. The url.Error value’s Timeout method will report true if the request timed out.
When err is nil, resp always contains a non-nil resp.Body. Caller should close resp.Body when done reading from it.
To make a request with custom headers, use NewRequest and Client.Do.
To make a request with a specified context.Context, use NewRequestWithContext and Client.Do.
func Head
1func (c *Client) Head(url string) (resp *Response, err error)
Head issues a HEAD to the specified URL. If the response is one of the following redirect codes, Head follows the redirect after calling the Client's CheckRedirect function:
301 (Moved Permanently)
302 (Found)
303 (See Other)
307 (Temporary Redirect)
308 (Permanent Redirect)
To make a request with a specified context.Context, use NewRequestWithContext and Client.Do.
func Post
1func (c *Client) Post(url, contentType string, body io.Reader) (resp *Response, err error)
Post issues a POST to the specified URL.
Caller should close resp.Body when done reading from it.
If the provided body is an io.Closer, it is closed after the request.
To set custom headers, use NewRequest and Client.Do.
To make a request with a specified context.Context, use NewRequestWithContext and Client.Do.
See the Client.Do method documentation for details on how redirects are handled.
func PostForm
1func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error)
PostForm issues a POST to the specified URL, with data's keys and values URL-encoded as the request body.
The Content-Type header is set to application/x-www-form-urlencoded. To set other headers, use NewRequest and Client.Do.
When err is nil, resp always contains a non-nil resp.Body. Caller should close resp.Body when done reading from it.
See the Client.Do method documentation for details on how redirects are handled.
To make a request with a specified context.Context, use NewRequestWithContext and Client.Do.
type CloseNotifier
1type CloseNotifier interface {
2 // CloseNotify returns a channel that receives at most a
3 // single value (true) when the client connection has gone
4 // away.
5 //
6 // CloseNotify may wait to notify until Request.Body has been
7 // fully read.
8 //
9 // After the Handler has returned, there is no guarantee
10 // that the channel receives a value.
11 //
12 // If the protocol is HTTP/1.1 and CloseNotify is called while
13 // processing an idempotent request (such a GET) while
14 // HTTP/1.1 pipelining is in use, the arrival of a subsequent
15 // pipelined request may cause a value to be sent on the
16 // returned channel. In practice HTTP/1.1 pipelining is not
17 // enabled in browsers and not seen often in the wild. If this
18 // is a problem, use HTTP/2 or only use CloseNotify on methods
19 // such as POST.
20 CloseNotify() <-chan bool
21}
The CloseNotifier interface is implemented by ResponseWriters which allow detecting when the underlying connection has gone away.
This mechanism can be used to cancel long operations on the server if the client has disconnected before the response is ready.
Deprecated: the CloseNotifier interface predates Go’s context package. New code should use Request.Context instead.
type Cookie
1type Cookie struct {
2 Name string
3 Value string
4
5 Path string // optional
6 Domain string // optional
7 Expires time.Time // optional
8 RawExpires string // for reading cookies only
9
10 // MaxAge=0 means no 'Max-Age' attribute specified.
11 // MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'
12 // MaxAge>0 means Max-Age attribute present and given in seconds
13 MaxAge int
14 Secure bool
15 HttpOnly bool
16 SameSite SameSite
17 Raw string
18 Unparsed []string // Raw text of unparsed attribute-value pairs
19}
A Cookie represents an HTTP cookie as sent in the Set-Cookie header of an HTTP response or the Cookie header of an HTTP request.
See https://tools.ietf.org/html/rfc6265 for details.
func String
1func (c *Cookie) String() string
String returns the serialization of the cookie for use in a Cookie header (if only Name and Value are set) or a Set-Cookie response header (if other fields are set). If c is nil or c.Name is invalid, the empty string is returned.
type CookieJar
1type CookieJar interface {
2 // SetCookies handles the receipt of the cookies in a reply for the
3 // given URL. It may or may not choose to save the cookies, depending
4 // on the jar's policy and implementation.
5 SetCookies(u *url.URL, cookies []*Cookie)
6
7 // Cookies returns the cookies to send in a request for the given URL.
8 // It is up to the implementation to honor the standard cookie use
9 // restrictions such as in RFC 6265.
10 Cookies(u *url.URL) []*Cookie
11}
A CookieJar manages storage and use of cookies in HTTP requests.
Implementations of CookieJar must be safe for concurrent use by multiple goroutines.
The net/http/cookiejar package provides a CookieJar implementation.
type File
1type File interface {
2 io.Closer
3 io.Reader
4 io.Seeker
5 Readdir(count int) ([]fs.FileInfo, error)
6 Stat() (fs.FileInfo, error)
7}
A File is returned by a FileSystem’s Open method and can be served by the FileServer implementation.
The methods should behave the same as those on an *os.File.
type FileSystem
1type FileSystem interface {
2 Open(name string) (File, error)
3}
A FileSystem implements access to a collection of named files. The elements in a file path are separated by slash (’/’, U+002F) characters, regardless of host operating system convention. See the FileServer function to convert a FileSystem to a Handler.
This interface predates the fs.FS interface, which can be used instead: the FS adapter function converts an fs.FS to a FileSystem.
type Flusher
1type Flusher interface {
2 // Flush sends any buffered data to the client.
3 Flush()
4}
The Flusher interface is implemented by ResponseWriters that allow an HTTP handler to flush buffered data to the client.
The default HTTP/1.x and HTTP/2 ResponseWriter implementations support Flusher, but ResponseWriter wrappers may not. Handlers should always test for this ability at runtime.
Note that even for ResponseWriters that support Flush, if the client is connected through an HTTP proxy, the buffered data may not reach the client until the response completes.
type Handler
1type Handler interface {
2 ServeHTTP(ResponseWriter, *Request)
3}
A Handler responds to an HTTP request.
ServeHTTP should write reply headers and data to the ResponseWriter and then return. Returning signals that the request is finished; it is not valid to use the ResponseWriter or read from the Request.Body after or concurrently with the completion of the ServeHTTP call.
Depending on the HTTP client software, HTTP protocol version, and any intermediaries between the client and the Go server, it may not be possible to read from the Request.Body after writing to the ResponseWriter. Cautious handlers should read the Request.Body first, and then reply.
Except for reading the body, handlers should not modify the provided Request.
If ServeHTTP panics, the server (the caller of ServeHTTP) assumes that the effect of the panic was isolated to the active request. It recovers the panic, logs a stack trace to the server error log, and either closes the network connection or sends an HTTP/2 RST_STREAM, depending on the HTTP protocol. To abort a handler so the client sees an interrupted response but the server doesn’t log an error, panic with the value ErrAbortHandler.
type Hijacker
1type Hijacker interface {
2 // Hijack lets the caller take over the connection.
3 // After a call to Hijack the HTTP server library
4 // will not do anything else with the connection.
5 //
6 // It becomes the caller's responsibility to manage
7 // and close the connection.
8 //
9 // The returned net.Conn may have read or write deadlines
10 // already set, depending on the configuration of the
11 // Server. It is the caller's responsibility to set
12 // or clear those deadlines as needed.
13 //
14 // The returned bufio.Reader may contain unprocessed buffered
15 // data from the client.
16 //
17 // After a call to Hijack, the original Request.Body must not
18 // be used. The original Request's Context remains valid and
19 // is not canceled until the Request's ServeHTTP method
20 // returns.
21 Hijack() (net.Conn, *bufio.ReadWriter, error)
22}
The Hijacker interface is implemented by ResponseWriters that allow an HTTP handler to take over the connection.
The default ResponseWriter for HTTP/1.x connections supports Hijacker, but HTTP/2 connections intentionally do not. ResponseWriter wrappers may also not support Hijacker. Handlers should always test for this ability at runtime.
type Pusher
1type Pusher interface {
2 // Push initiates an HTTP/2 server push. This constructs a synthetic
3 // request using the given target and options, serializes that request
4 // into a PUSH_PROMISE frame, then dispatches that request using the
5 // server's request handler. If opts is nil, default options are used.
6 //
7 // The target must either be an absolute path (like "/path") or an absolute
8 // URL that contains a valid host and the same scheme as the parent request.
9 // If the target is a path, it will inherit the scheme and host of the
10 // parent request.
11 //
12 // The HTTP/2 spec disallows recursive pushes and cross-authority pushes.
13 // Push may or may not detect these invalid pushes; however, invalid
14 // pushes will be detected and canceled by conforming clients.
15 //
16 // Handlers that wish to push URL X should call Push before sending any
17 // data that may trigger a request for URL X. This avoids a race where the
18 // client issues requests for X before receiving the PUSH_PROMISE for X.
19 //
20 // Push will run in a separate goroutine making the order of arrival
21 // non-deterministic. Any required synchronization needs to be implemented
22 // by the caller.
23 //
24 // Push returns ErrNotSupported if the client has disabled push or if push
25 // is not supported on the underlying connection.
26 Push(target string, opts *PushOptions) error
27}
Pusher is the interface implemented by ResponseWriters that support HTTP/2 server push. For more background, see https://tools.ietf.org/html/rfc7540#section-8.2.
type Request
1type Request struct {
2 // Method specifies the HTTP method (GET, POST, PUT, etc.).
3 // For client requests, an empty string means GET.
4 //
5 // Go's HTTP client does not support sending a request with
6 // the CONNECT method. See the documentation on Transport for
7 // details.
8 Method string
9
10 // URL specifies either the URI being requested (for server
11 // requests) or the URL to access (for client requests).
12 //
13 // For server requests, the URL is parsed from the URI
14 // supplied on the Request-Line as stored in RequestURI. For
15 // most requests, fields other than Path and RawQuery will be
16 // empty. (See RFC 7230, Section 5.3)
17 //
18 // For client requests, the URL's Host specifies the server to
19 // connect to, while the Request's Host field optionally
20 // specifies the Host header value to send in the HTTP
21 // request.
22 URL *url.URL
23
24 // The protocol version for incoming server requests.
25 //
26 // For client requests, these fields are ignored. The HTTP
27 // client code always uses either HTTP/1.1 or HTTP/2.
28 // See the docs on Transport for details.
29 Proto string // "HTTP/1.0"
30 ProtoMajor int // 1
31 ProtoMinor int // 0
32
33 // Header contains the request header fields either received
34 // by the server or to be sent by the client.
35 //
36 // If a server received a request with header lines,
37 //
38 // Host: example.com
39 // accept-encoding: gzip, deflate
40 // Accept-Language: en-us
41 // fOO: Bar
42 // foo: two
43 //
44 // then
45 //
46 // Header = map[string][]string{
47 // "Accept-Encoding": {"gzip, deflate"},
48 // "Accept-Language": {"en-us"},
49 // "Foo": {"Bar", "two"},
50 // }
51 //
52 // For incoming requests, the Host header is promoted to the
53 // Request.Host field and removed from the Header map.
54 //
55 // HTTP defines that header names are case-insensitive. The
56 // request parser implements this by using CanonicalHeaderKey,
57 // making the first character and any characters following a
58 // hyphen uppercase and the rest lowercase.
59 //
60 // For client requests, certain headers such as Content-Length
61 // and Connection are automatically written when needed and
62 // values in Header may be ignored. See the documentation
63 // for the Request.Write method.
64 Header Header
65
66 // Body is the request's body.
67 //
68 // For client requests, a nil body means the request has no
69 // body, such as a GET request. The HTTP Client's Transport
70 // is responsible for calling the Close method.
71 //
72 // For server requests, the Request Body is always non-nil
73 // but will return EOF immediately when no body is present.
74 // The Server will close the request body. The ServeHTTP
75 // Handler does not need to.
76 //
77 // Body must allow Read to be called concurrently with Close.
78 // In particular, calling Close should unblock a Read waiting
79 // for input.
80 Body io.ReadCloser
81
82 // GetBody defines an optional func to return a new copy of
83 // Body. It is used for client requests when a redirect requires
84 // reading the body more than once. Use of GetBody still
85 // requires setting Body.
86 //
87 // For server requests, it is unused.
88 GetBody func() (io.ReadCloser, error)
89
90 // ContentLength records the length of the associated content.
91 // The value -1 indicates that the length is unknown.
92 // Values >= 0 indicate that the given number of bytes may
93 // be read from Body.
94 //
95 // For client requests, a value of 0 with a non-nil Body is
96 // also treated as unknown.
97 ContentLength int64
98
99 // TransferEncoding lists the transfer encodings from outermost to
100 // innermost. An empty list denotes the "identity" encoding.
101 // TransferEncoding can usually be ignored; chunked encoding is
102 // automatically added and removed as necessary when sending and
103 // receiving requests.
104 TransferEncoding []string
105
106 // Close indicates whether to close the connection after
107 // replying to this request (for servers) or after sending this
108 // request and reading its response (for clients).
109 //
110 // For server requests, the HTTP server handles this automatically
111 // and this field is not needed by Handlers.
112 //
113 // For client requests, setting this field prevents re-use of
114 // TCP connections between requests to the same hosts, as if
115 // Transport.DisableKeepAlives were set.
116 Close bool
117
118 // For server requests, Host specifies the host on which the
119 // URL is sought. For HTTP/1 (per RFC 7230, section 5.4), this
120 // is either the value of the "Host" header or the host name
121 // given in the URL itself. For HTTP/2, it is the value of the
122 // ":authority" pseudo-header field.
123 // It may be of the form "host:port". For international domain
124 // names, Host may be in Punycode or Unicode form. Use
125 // golang.org/x/net/idna to convert it to either format if
126 // needed.
127 // To prevent DNS rebinding attacks, server Handlers should
128 // validate that the Host header has a value for which the
129 // Handler considers itself authoritative. The included
130 // ServeMux supports patterns registered to particular host
131 // names and thus protects its registered Handlers.
132 //
133 // For client requests, Host optionally overrides the Host
134 // header to send. If empty, the Request.Write method uses
135 // the value of URL.Host. Host may contain an international
136 // domain name.
137 Host string
138
139 // Form contains the parsed form data, including both the URL
140 // field's query parameters and the PATCH, POST, or PUT form data.
141 // This field is only available after ParseForm is called.
142 // The HTTP client ignores Form and uses Body instead.
143 Form url.Values
144
145 // PostForm contains the parsed form data from PATCH, POST
146 // or PUT body parameters.
147 //
148 // This field is only available after ParseForm is called.
149 // The HTTP client ignores PostForm and uses Body instead.
150 PostForm url.Values
151
152 // MultipartForm is the parsed multipart form, including file uploads.
153 // This field is only available after ParseMultipartForm is called.
154 // The HTTP client ignores MultipartForm and uses Body instead.
155 MultipartForm *multipart.Form
156
157 // Trailer specifies additional headers that are sent after the request
158 // body.
159 //
160 // For server requests, the Trailer map initially contains only the
161 // trailer keys, with nil values. (The client declares which trailers it
162 // will later send.) While the handler is reading from Body, it must
163 // not reference Trailer. After reading from Body returns EOF, Trailer
164 // can be read again and will contain non-nil values, if they were sent
165 // by the client.
166 //
167 // For client requests, Trailer must be initialized to a map containing
168 // the trailer keys to later send. The values may be nil or their final
169 // values. The ContentLength must be 0 or -1, to send a chunked request.
170 // After the HTTP request is sent the map values can be updated while
171 // the request body is read. Once the body returns EOF, the caller must
172 // not mutate Trailer.
173 //
174 // Few HTTP clients, servers, or proxies support HTTP trailers.
175 Trailer Header
176
177 // RemoteAddr allows HTTP servers and other software to record
178 // the network address that sent the request, usually for
179 // logging. This field is not filled in by ReadRequest and
180 // has no defined format. The HTTP server in this package
181 // sets RemoteAddr to an "IP:port" address before invoking a
182 // handler.
183 // This field is ignored by the HTTP client.
184 RemoteAddr string
185
186 // RequestURI is the unmodified request-target of the
187 // Request-Line (RFC 7230, Section 3.1.1) as sent by the client
188 // to a server. Usually the URL field should be used instead.
189 // It is an error to set this field in an HTTP client request.
190 RequestURI string
191
192 // TLS allows HTTP servers and other software to record
193 // information about the TLS connection on which the request
194 // was received. This field is not filled in by ReadRequest.
195 // The HTTP server in this package sets the field for
196 // TLS-enabled connections before invoking a handler;
197 // otherwise it leaves the field nil.
198 // This field is ignored by the HTTP client.
199 TLS *tls.ConnectionState
200
201 // Cancel is an optional channel whose closure indicates that the client
202 // request should be regarded as canceled. Not all implementations of
203 // RoundTripper may support Cancel.
204 //
205 // For server requests, this field is not applicable.
206 //
207 // Deprecated: Set the Request's context with NewRequestWithContext
208 // instead. If a Request's Cancel field and context are both
209 // set, it is undefined whether Cancel is respected.
210 Cancel <-chan struct{}
211
212 // Response is the redirect response which caused this request
213 // to be created. This field is only populated during client
214 // redirects.
215 Response *Response
216}
A Request represents an HTTP request received by a server or to be sent by a client.
The field semantics differ slightly between client and server usage. In addition to the notes on the fields below, see the documentation for Request.Write and RoundTripper.
func AddCookie
1func (r *Request) AddCookie(c *Cookie)
AddCookie adds a cookie to the request. Per RFC 6265 section 5.4, AddCookie does not attach more than one Cookie header field. That means all cookies, if any, are written into the same line, separated by semicolon. AddCookie only sanitizes c's name and value, and does not sanitize a Cookie header already present in the request.
func BasicAuth
1func (r *Request) BasicAuth() (username, password string, ok bool)
BasicAuth returns the username and password provided in the request's Authorization header, if the request uses HTTP Basic Authentication. See RFC 2617, Section 2.
func Clone
1func (r *Request) Clone(ctx context.Context) *Request
Clone returns a deep copy of r with its context changed to ctx. The provided ctx must be non-nil.
For an outgoing client request, the context controls the entire lifetime of a request and its response: obtaining a connection, sending the request, and reading the response headers and body.
func Context
1func (r *Request) Context() context.Context
Context returns the request's context. To change the context, use Clone or WithContext.
The returned context is always non-nil; it defaults to the background context.
For outgoing client requests, the context controls cancellation.
For incoming server requests, the context is canceled when the client’s connection closes, the request is canceled (with HTTP/2), or when the ServeHTTP method returns.
func Cookie
1func (r *Request) Cookie(name string) (*Cookie, error)
Cookie returns the named cookie provided in the request or ErrNoCookie if not found. If multiple cookies match the given name, only one cookie will be returned.
func Cookies
1func (r *Request) Cookies() []*Cookie
Cookies parses and returns the HTTP cookies sent with the request.
func FormFile
1func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error)
FormFile returns the first file for the provided form key. FormFile calls ParseMultipartForm and ParseForm if necessary.
func FormValue
1func (r *Request) FormValue(key string) string
FormValue returns the first value for the named component of the query. POST and PUT body parameters take precedence over URL query string values. FormValue calls ParseMultipartForm and ParseForm if necessary and ignores any errors returned by these functions. If key is not present, FormValue returns the empty string. To access multiple values of the same key, call ParseForm and then inspect Request.Form directly.
func MultipartReader
1func (r *Request) MultipartReader() (*multipart.Reader, error)
MultipartReader returns a MIME multipart reader if this is a multipart/form-data or a multipart/mixed POST request, else returns nil and an error. Use this function instead of ParseMultipartForm to process the request body as a stream.
func ParseForm
1func (r *Request) ParseForm() error
ParseForm populates r.Form and r.PostForm.
For all requests, ParseForm parses the raw query from the URL and updates r.Form.
For POST, PUT, and PATCH requests, it also reads the request body, parses it as a form and puts the results into both r.PostForm and r.Form. Request body parameters take precedence over URL query string values in r.Form.
If the request Body’s size has not already been limited by MaxBytesReader, the size is capped at 10MB.
For other HTTP methods, or when the Content-Type is not application/x-www-form-urlencoded, the request Body is not read, and r.PostForm is initialized to a non-nil, empty value.
ParseMultipartForm calls ParseForm automatically. ParseForm is idempotent.
func ParseMultipartForm
1func (r *Request) ParseMultipartForm(maxMemory int64) error
ParseMultipartForm parses a request body as multipart/form-data. The whole request body is parsed and up to a total of maxMemory bytes of its file parts are stored in memory, with the remainder stored on disk in temporary files. ParseMultipartForm calls ParseForm if necessary. If ParseForm returns an error, ParseMultipartForm returns it but also continues parsing the request body. After one call to ParseMultipartForm, subsequent calls have no effect.
func PostFormValue
1func (r *Request) PostFormValue(key string) string
PostFormValue returns the first value for the named component of the POST, PATCH, or PUT request body. URL query parameters are ignored. PostFormValue calls ParseMultipartForm and ParseForm if necessary and ignores any errors returned by these functions. If key is not present, PostFormValue returns the empty string.
func ProtoAtLeast
1func (r *Request) ProtoAtLeast(major, minor int) bool
ProtoAtLeast reports whether the HTTP protocol used in the request is at least major.minor.
func Referer
1func (r *Request) Referer() string
Referer returns the referring URL, if sent in the request.
Referer is misspelled as in the request itself, a mistake from the earliest days of HTTP. This value can also be fetched from the Header map as Header[“Referer”]; the benefit of making it available as a method is that the compiler can diagnose programs that use the alternate (correct English) spelling req.Referrer() but cannot diagnose programs that use Header[“Referrer”].
func SetBasicAuth
1func (r *Request) SetBasicAuth(username, password string)
SetBasicAuth sets the request's Authorization header to use HTTP Basic Authentication with the provided username and password.
With HTTP Basic Authentication the provided username and password are not encrypted. It should generally only be used in an HTTPS request.
The username may not contain a colon. Some protocols may impose additional requirements on pre-escaping the username and password. For instance, when used with OAuth2, both arguments must be URL encoded first with url.QueryEscape.
func UserAgent
1func (r *Request) UserAgent() string
UserAgent returns the client's User-Agent, if sent in the request.
func WithContext
1func (r *Request) WithContext(ctx context.Context) *Request
WithContext returns a shallow copy of r with its context changed to ctx. The provided ctx must be non-nil.
For outgoing client request, the context controls the entire lifetime of a request and its response: obtaining a connection, sending the request, and reading the response headers and body.
To create a new request with a context, use NewRequestWithContext. To make a deep copy of a request with a new context, use Request.Clone.
func Write
1func (r *Request) Write(w io.Writer) error
Write writes an HTTP/1.1 request, which is the header and body, in wire format. This method consults the following fields of the request:
Host
URL
Method (defaults to "GET")
Header
ContentLength
TransferEncoding
Body
If Body is present, Content-Length is <= 0 and TransferEncoding hasn’t been set to “identity”, Write adds “Transfer-Encoding: chunked” to the header. Body is closed after it is sent.
func WriteProxy
1func (r *Request) WriteProxy(w io.Writer) error
WriteProxy is like Write but writes the request in the form expected by an HTTP proxy. In particular, WriteProxy writes the initial Request-URI line of the request with an absolute URI, per section 5.3 of RFC 7230, including the scheme and host. In either case, WriteProxy also writes a Host header, using either r.Host or r.URL.Host.
type Response
1type Response struct {
2 Status string // e.g. "200 OK"
3 StatusCode int // e.g. 200
4 Proto string // e.g. "HTTP/1.0"
5 ProtoMajor int // e.g. 1
6 ProtoMinor int // e.g. 0
7
8 // Header maps header keys to values. If the response had multiple
9 // headers with the same key, they may be concatenated, with comma
10 // delimiters. (RFC 7230, section 3.2.2 requires that multiple headers
11 // be semantically equivalent to a comma-delimited sequence.) When
12 // Header values are duplicated by other fields in this struct (e.g.,
13 // ContentLength, TransferEncoding, Trailer), the field values are
14 // authoritative.
15 //
16 // Keys in the map are canonicalized (see CanonicalHeaderKey).
17 Header Header
18
19 // Body represents the response body.
20 //
21 // The response body is streamed on demand as the Body field
22 // is read. If the network connection fails or the server
23 // terminates the response, Body.Read calls return an error.
24 //
25 // The http Client and Transport guarantee that Body is always
26 // non-nil, even on responses without a body or responses with
27 // a zero-length body. It is the caller's responsibility to
28 // close Body. The default HTTP client's Transport may not
29 // reuse HTTP/1.x "keep-alive" TCP connections if the Body is
30 // not read to completion and closed.
31 //
32 // The Body is automatically dechunked if the server replied
33 // with a "chunked" Transfer-Encoding.
34 //
35 // As of Go 1.12, the Body will also implement io.Writer
36 // on a successful "101 Switching Protocols" response,
37 // as used by WebSockets and HTTP/2's "h2c" mode.
38 Body io.ReadCloser
39
40 // ContentLength records the length of the associated content. The
41 // value -1 indicates that the length is unknown. Unless Request.Method
42 // is "HEAD", values >= 0 indicate that the given number of bytes may
43 // be read from Body.
44 ContentLength int64
45
46 // Contains transfer encodings from outer-most to inner-most. Value is
47 // nil, means that "identity" encoding is used.
48 TransferEncoding []string
49
50 // Close records whether the header directed that the connection be
51 // closed after reading Body. The value is advice for clients: neither
52 // ReadResponse nor Response.Write ever closes a connection.
53 Close bool
54
55 // Uncompressed reports whether the response was sent compressed but
56 // was decompressed by the http package. When true, reading from
57 // Body yields the uncompressed content instead of the compressed
58 // content actually set from the server, ContentLength is set to -1,
59 // and the "Content-Length" and "Content-Encoding" fields are deleted
60 // from the responseHeader. To get the original response from
61 // the server, set Transport.DisableCompression to true.
62 Uncompressed bool
63
64 // Trailer maps trailer keys to values in the same
65 // format as Header.
66 //
67 // The Trailer initially contains only nil values, one for
68 // each key specified in the server's "Trailer" header
69 // value. Those values are not added to Header.
70 //
71 // Trailer must not be accessed concurrently with Read calls
72 // on the Body.
73 //
74 // After Body.Read has returned io.EOF, Trailer will contain
75 // any trailer values sent by the server.
76 Trailer Header
77
78 // Request is the request that was sent to obtain this Response.
79 // Request's Body is nil (having already been consumed).
80 // This is only populated for Client requests.
81 Request *Request
82
83 // TLS contains information about the TLS connection on which the
84 // response was received. It is nil for unencrypted responses.
85 // The pointer is shared between responses and should not be
86 // modified.
87 TLS *tls.ConnectionState
88}
Response represents the response from an HTTP request.
The Client and Transport return Responses from servers once the response headers have been received. The response body is streamed on demand as the Body field is read.
func Cookies
1func (r *Response) Cookies() []*Cookie
Cookies parses and returns the cookies set in the Set-Cookie headers.
func Location
1func (r *Response) Location() (*url.URL, error)
Location returns the URL of the response's "Location" header, if present. Relative redirects are resolved relative to the Response's Request. ErrNoLocation is returned if no Location header is present.
func ProtoAtLeast
1func (r *Response) ProtoAtLeast(major, minor int) bool
ProtoAtLeast reports whether the HTTP protocol used in the response is at least major.minor.
func Write
1func (r *Response) Write(w io.Writer) error
Write writes r to w in the HTTP/1.x server response format, including the status line, headers, body, and optional trailer.
This method consults the following fields of the response r:
StatusCode
ProtoMajor
ProtoMinor
Request.Method
TransferEncoding
Trailer
Body
ContentLength
Header, values for non-canonical keys will have unpredictable behavior
The Response Body is closed after it is sent.
type ResponseWriter
1type ResponseWriter interface {
2 // Header returns the header map that will be sent by
3 // WriteHeader. The Header map also is the mechanism with which
4 // Handlers can set HTTP trailers.
5 //
6 // Changing the header map after a call to WriteHeader (or
7 // Write) has no effect unless the HTTP status code was of the
8 // 1xx class or the modified headers are trailers.
9 //
10 // There are two ways to set Trailers. The preferred way is to
11 // predeclare in the headers which trailers you will later
12 // send by setting the "Trailer" header to the names of the
13 // trailer keys which will come later. In this case, those
14 // keys of the Header map are treated as if they were
15 // trailers. See the example. The second way, for trailer
16 // keys not known to the Handler until after the first Write,
17 // is to prefix the Header map keys with the TrailerPrefix
18 // constant value. See TrailerPrefix.
19 //
20 // To suppress automatic response headers (such as "Date"), set
21 // their value to nil.
22 Header() Header
23
24 // Write writes the data to the connection as part of an HTTP reply.
25 //
26 // If WriteHeader has not yet been called, Write calls
27 // WriteHeader(http.StatusOK) before writing the data. If the Header
28 // does not contain a Content-Type line, Write adds a Content-Type set
29 // to the result of passing the initial 512 bytes of written data to
30 // DetectContentType. Additionally, if the total size of all written
31 // data is under a few KB and there are no Flush calls, the
32 // Content-Length header is added automatically.
33 //
34 // Depending on the HTTP protocol version and the client, calling
35 // Write or WriteHeader may prevent future reads on the
36 // Request.Body. For HTTP/1.x requests, handlers should read any
37 // needed request body data before writing the response. Once the
38 // headers have been flushed (due to either an explicit Flusher.Flush
39 // call or writing enough data to trigger a flush), the request body
40 // may be unavailable. For HTTP/2 requests, the Go HTTP server permits
41 // handlers to continue to read the request body while concurrently
42 // writing the response. However, such behavior may not be supported
43 // by all HTTP/2 clients. Handlers should read before writing if
44 // possible to maximize compatibility.
45 Write([]byte) (int, error)
46
47 // WriteHeader sends an HTTP response header with the provided
48 // status code.
49 //
50 // If WriteHeader is not called explicitly, the first call to Write
51 // will trigger an implicit WriteHeader(http.StatusOK).
52 // Thus explicit calls to WriteHeader are mainly used to
53 // send error codes or 1xx informational responses.
54 //
55 // The provided code must be a valid HTTP 1xx-5xx status code.
56 // Any number of 1xx headers may be written, followed by at most
57 // one 2xx-5xx header. 1xx headers are sent immediately, but 2xx-5xx
58 // headers may be buffered. Use the Flusher interface to send
59 // buffered data. The header map is cleared when 2xx-5xx headers are
60 // sent, but not with 1xx headers.
61 //
62 // The server will automatically send a 100 (Continue) header
63 // on the first read from the request body if the request has
64 // an "Expect: 100-continue" header.
65 WriteHeader(statusCode int)
66}
A ResponseWriter interface is used by an HTTP handler to construct an HTTP response.
A ResponseWriter may not be used after the Handler.ServeHTTP method has returned.
type RoundTripper
1type RoundTripper interface {
2 // RoundTrip executes a single HTTP transaction, returning
3 // a Response for the provided Request.
4 //
5 // RoundTrip should not attempt to interpret the response. In
6 // particular, RoundTrip must return err == nil if it obtained
7 // a response, regardless of the response's HTTP status code.
8 // A non-nil err should be reserved for failure to obtain a
9 // response. Similarly, RoundTrip should not attempt to
10 // handle higher-level protocol details such as redirects,
11 // authentication, or cookies.
12 //
13 // RoundTrip should not modify the request, except for
14 // consuming and closing the Request's Body. RoundTrip may
15 // read fields of the request in a separate goroutine. Callers
16 // should not mutate or reuse the request until the Response's
17 // Body has been closed.
18 //
19 // RoundTrip must always close the body, including on errors,
20 // but depending on the implementation may do so in a separate
21 // goroutine even after RoundTrip returns. This means that
22 // callers wanting to reuse the body for subsequent requests
23 // must arrange to wait for the Close call before doing so.
24 //
25 // The Request's URL and Header fields must be initialized.
26 RoundTrip(*Request) (*Response, error)
27}
RoundTripper is an interface representing the ability to execute a single HTTP transaction, obtaining the Response for a given Request.
A RoundTripper must be safe for concurrent use by multiple goroutines.
type ServeMux
1type ServeMux struct {
2}
ServeMux is an HTTP request multiplexer. It matches the URL of each incoming request against a list of registered patterns and calls the handler for the pattern that most closely matches the URL.
Patterns name fixed, rooted paths, like “/favicon.ico”, or rooted subtrees, like “/images/” (note the trailing slash). Longer patterns take precedence over shorter ones, so that if there are handlers registered for both “/images/” and “/images/thumbnails/”, the latter handler will be called for paths beginning “/images/thumbnails/” and the former will receive requests for any other paths in the “/images/” subtree.
Note that since a pattern ending in a slash names a rooted subtree, the pattern “/” matches all paths not matched by other registered patterns, not just the URL with Path == “/”.
If a subtree has been registered and a request is received naming the subtree root without its trailing slash, ServeMux redirects that request to the subtree root (adding the trailing slash). This behavior can be overridden with a separate registration for the path without the trailing slash. For example, registering “/images/” causes ServeMux to redirect a request for “/images” to “/images/”, unless “/images” has been registered separately.
Patterns may optionally begin with a host name, restricting matches to URLs on that host only. Host-specific patterns take precedence over general patterns, so that a handler might register for the two patterns “/codesearch” and “codesearch.google.com/” without also taking over requests for “http://www.google.com/".
ServeMux also takes care of sanitizing the URL request path and the Host header, stripping the port number and redirecting any request containing . or .. elements or repeated slashes to an equivalent, cleaner URL.
func Handle
1func (mux *ServeMux) Handle(pattern string, handler Handler)
Handle registers the handler for the given pattern. If a handler already exists for pattern, Handle panics.
1mux := http.NewServeMux()
2mux.Handle("/api/", apiHandler{})
3mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
4
5 if req.URL.Path != "/" {
6 http.NotFound(w, req)
7 return
8 }
9 fmt.Fprintf(w, "Welcome to the home page!")
10})
func HandleFunc
1func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))
HandleFunc registers the handler function for the given pattern.
func Handler
1func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string)
Handler returns the handler to use for the given request, consulting r.Method, r.Host, and r.URL.Path. It always returns a non-nil handler. If the path is not in its canonical form, the handler will be an internally-generated handler that redirects to the canonical path. If the host contains a port, it is ignored when matching handlers.
The path and host are used unchanged for CONNECT requests.
Handler also returns the registered pattern that matches the request or, in the case of internally-generated redirects, the pattern that will match after following the redirect.
If there is no registered handler that applies to the request, Handler returns a “page not found” handler and an empty pattern.
func ServeHTTP
1func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request)
ServeHTTP dispatches the request to the handler whose pattern most closely matches the request URL.