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) CookiesNamed(name string) []*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) PathValue(name string) string
- 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) SetPathValue(name, value 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)
- type Transport
Functions
func Handle
1func Handle(pattern string, handler Handler)Handle registers the handler for the given pattern in 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 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) errorListenAndServe 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 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) errorServe 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 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.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 [Client.Transport] does not have a Client.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. The Body may be closed asynchronously after Do returns.
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.CheckRedirect] function:
301 (Moved Permanently)
302 (Found)
303 (See Other)
307 (Temporary Redirect)
308 (Permanent Redirect)
An error is returned if the [Client.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.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 as 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 Quoted bool // indicates whether the Value was originally quoted
5
6 Path string // optional
7 Domain string // optional
8 Expires time.Time // optional
9 RawExpires string // for reading cookies only
10
11 // MaxAge=0 means no 'Max-Age' attribute specified.
12 // MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'
13 // MaxAge>0 means Max-Age attribute present and given in seconds
14 MaxAge int
15 Secure bool
16 HttpOnly bool
17 SameSite SameSite
18 Partitioned bool
19 Raw string
20 Unparsed []string // Raw text of unparsed attribute-value pairs
21}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() stringString 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.
[Handler.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 Method string
5
6 // URL specifies either the URI being requested (for server
7 // requests) or the URL to access (for client requests).
8 //
9 // For server requests, the URL is parsed from the URI
10 // supplied on the Request-Line as stored in RequestURI. For
11 // most requests, fields other than Path and RawQuery will be
12 // empty. (See RFC 7230, Section 5.3)
13 //
14 // For client requests, the URL's Host specifies the server to
15 // connect to, while the Request's Host field optionally
16 // specifies the Host header value to send in the HTTP
17 // request.
18 URL *url.URL
19
20 // The protocol version for incoming server requests.
21 //
22 // For client requests, these fields are ignored. The HTTP
23 // client code always uses either HTTP/1.1 or HTTP/2.
24 // See the docs on Transport for details.
25 Proto string // "HTTP/1.0"
26 ProtoMajor int // 1
27 ProtoMinor int // 0
28
29 // Header contains the request header fields either received
30 // by the server or to be sent by the client.
31 //
32 // If a server received a request with header lines,
33 //
34 // Host: example.com
35 // accept-encoding: gzip, deflate
36 // Accept-Language: en-us
37 // fOO: Bar
38 // foo: two
39 //
40 // then
41 //
42 // Header = map[string][]string{
43 // "Accept-Encoding": {"gzip, deflate"},
44 // "Accept-Language": {"en-us"},
45 // "Foo": {"Bar", "two"},
46 // }
47 //
48 // For incoming requests, the Host header is promoted to the
49 // Request.Host field and removed from the Header map.
50 //
51 // HTTP defines that header names are case-insensitive. The
52 // request parser implements this by using CanonicalHeaderKey,
53 // making the first character and any characters following a
54 // hyphen uppercase and the rest lowercase.
55 //
56 // For client requests, certain headers such as Content-Length
57 // and Connection are automatically written when needed and
58 // values in Header may be ignored. See the documentation
59 // for the Request.Write method.
60 Header Header
61
62 // Body is the request's body.
63 //
64 // For client requests, a nil body means the request has no
65 // body, such as a GET request. The HTTP Client's Transport
66 // is responsible for calling the Close method.
67 //
68 // For server requests, the Request Body is always non-nil
69 // but will return EOF immediately when no body is present.
70 // The Server will close the request body. The ServeHTTP
71 // Handler does not need to.
72 //
73 // Body must allow Read to be called concurrently with Close.
74 // In particular, calling Close should unblock a Read waiting
75 // for input.
76 Body io.ReadCloser
77
78 // GetBody defines an optional func to return a new copy of
79 // Body. It is used for client requests when a redirect requires
80 // reading the body more than once. Use of GetBody still
81 // requires setting Body.
82 //
83 // For server requests, it is unused.
84 GetBody func() (io.ReadCloser, error)
85
86 // ContentLength records the length of the associated content.
87 // The value -1 indicates that the length is unknown.
88 // Values >= 0 indicate that the given number of bytes may
89 // be read from Body.
90 //
91 // For client requests, a value of 0 with a non-nil Body is
92 // also treated as unknown.
93 ContentLength int64
94
95 // TransferEncoding lists the transfer encodings from outermost to
96 // innermost. An empty list denotes the "identity" encoding.
97 // TransferEncoding can usually be ignored; chunked encoding is
98 // automatically added and removed as necessary when sending and
99 // receiving requests.
100 TransferEncoding []string
101
102 // Close indicates whether to close the connection after
103 // replying to this request (for servers) or after sending this
104 // request and reading its response (for clients).
105 //
106 // For server requests, the HTTP server handles this automatically
107 // and this field is not needed by Handlers.
108 //
109 // For client requests, setting this field prevents re-use of
110 // TCP connections between requests to the same hosts, as if
111 // Transport.DisableKeepAlives were set.
112 Close bool
113
114 // For server requests, Host specifies the host on which the
115 // URL is sought. For HTTP/1 (per RFC 7230, section 5.4), this
116 // is either the value of the "Host" header or the host name
117 // given in the URL itself. For HTTP/2, it is the value of the
118 // ":authority" pseudo-header field.
119 // It may be of the form "host:port". For international domain
120 // names, Host may be in Punycode or Unicode form. Use
121 // golang.org/x/net/idna to convert it to either format if
122 // needed.
123 // To prevent DNS rebinding attacks, server Handlers should
124 // validate that the Host header has a value for which the
125 // Handler considers itself authoritative. The included
126 // ServeMux supports patterns registered to particular host
127 // names and thus protects its registered Handlers.
128 //
129 // For client requests, Host optionally overrides the Host
130 // header to send. If empty, the Request.Write method uses
131 // the value of URL.Host. Host may contain an international
132 // domain name.
133 Host string
134
135 // Form contains the parsed form data, including both the URL
136 // field's query parameters and the PATCH, POST, or PUT form data.
137 // This field is only available after ParseForm is called.
138 // The HTTP client ignores Form and uses Body instead.
139 Form url.Values
140
141 // PostForm contains the parsed form data from PATCH, POST
142 // or PUT body parameters.
143 //
144 // This field is only available after ParseForm is called.
145 // The HTTP client ignores PostForm and uses Body instead.
146 PostForm url.Values
147
148 // MultipartForm is the parsed multipart form, including file uploads.
149 // This field is only available after ParseMultipartForm is called.
150 // The HTTP client ignores MultipartForm and uses Body instead.
151 MultipartForm *multipart.Form
152
153 // Trailer specifies additional headers that are sent after the request
154 // body.
155 //
156 // For server requests, the Trailer map initially contains only the
157 // trailer keys, with nil values. (The client declares which trailers it
158 // will later send.) While the handler is reading from Body, it must
159 // not reference Trailer. After reading from Body returns EOF, Trailer
160 // can be read again and will contain non-nil values, if they were sent
161 // by the client.
162 //
163 // For client requests, Trailer must be initialized to a map containing
164 // the trailer keys to later send. The values may be nil or their final
165 // values. The ContentLength must be 0 or -1, to send a chunked request.
166 // After the HTTP request is sent the map values can be updated while
167 // the request body is read. Once the body returns EOF, the caller must
168 // not mutate Trailer.
169 //
170 // Few HTTP clients, servers, or proxies support HTTP trailers.
171 Trailer Header
172
173 // RemoteAddr allows HTTP servers and other software to record
174 // the network address that sent the request, usually for
175 // logging. This field is not filled in by ReadRequest and
176 // has no defined format. The HTTP server in this package
177 // sets RemoteAddr to an "IP:port" address before invoking a
178 // handler.
179 // This field is ignored by the HTTP client.
180 RemoteAddr string
181
182 // RequestURI is the unmodified request-target of the
183 // Request-Line (RFC 7230, Section 3.1.1) as sent by the client
184 // to a server. Usually the URL field should be used instead.
185 // It is an error to set this field in an HTTP client request.
186 RequestURI string
187
188 // TLS allows HTTP servers and other software to record
189 // information about the TLS connection on which the request
190 // was received. This field is not filled in by ReadRequest.
191 // The HTTP server in this package sets the field for
192 // TLS-enabled connections before invoking a handler;
193 // otherwise it leaves the field nil.
194 // This field is ignored by the HTTP client.
195 TLS *tls.ConnectionState
196
197 // Cancel is an optional channel whose closure indicates that the client
198 // request should be regarded as canceled. Not all implementations of
199 // RoundTripper may support Cancel.
200 //
201 // For server requests, this field is not applicable.
202 //
203 // Deprecated: Set the Request's context with NewRequestWithContext
204 // instead. If a Request's Cancel field and context are both
205 // set, it is undefined whether Cancel is respected.
206 Cancel <-chan struct{}
207
208 // Response is the redirect response which caused this request
209 // to be created. This field is only populated during client
210 // redirects.
211 Response *Response
212
213 // Pattern is the [ServeMux] pattern that matched the request.
214 // It is empty if the request was not matched against a pattern.
215 Pattern string
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) *RequestClone returns a deep copy of r with its context changed to ctx. The provided ctx must be non-nil.
Clone only makes a shallow copy of the Body field.
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.ContextContext returns the request's context. To change the context, use Request.Clone or Request.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() []*CookieCookies parses and returns the HTTP cookies sent with the request.
func CookiesNamed
1func (r *Request) CookiesNamed(name string) []*CookieCookiesNamed parses and returns the named HTTP cookies sent with the request or an empty slice if none matched.
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 Request.ParseMultipartForm and Request.ParseForm if necessary.
func FormValue
1func (r *Request) FormValue(key string) stringFormValue returns the first value for the named component of the query. The precedence order: 1. application/x-www-form-urlencoded form body (POST, PUT, PATCH only) 2. query parameters (always) 3. multipart/form-data form body (always)
FormValue calls Request.ParseMultipartForm and Request.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 Request.ParseMultipartForm to process the request body as a stream.
func ParseForm
1func (r *Request) ParseForm() errorParseForm 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.
Request.ParseMultipartForm calls ParseForm automatically. ParseForm is idempotent.
func ParseMultipartForm
1func (r *Request) ParseMultipartForm(maxMemory int64) errorParseMultipartForm 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 Request.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 PathValue
1func (r *Request) PathValue(name string) stringPathValue returns the value for the named path wildcard in the ServeMux pattern that matched the request. It returns the empty string if the request was not matched against a pattern or there is no such wildcard in the pattern.
func PostFormValue
1func (r *Request) PostFormValue(key string) stringPostFormValue returns the first value for the named component of the POST, PUT, or PATCH request body. URL query parameters are ignored. PostFormValue calls Request.ParseMultipartForm and Request.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) boolProtoAtLeast reports whether the HTTP protocol used in the request is at least major.minor.
func Referer
1func (r *Request) Referer() stringReferer 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 SetPathValue
1func (r *Request) SetPathValue(name, value string)SetPathValue sets name to value, so that subsequent calls to r.PathValue(name) return value.
func UserAgent
1func (r *Request) UserAgent() stringUserAgent returns the client's User-Agent, if sent in the request.
func WithContext
1func (r *Request) WithContext(ctx context.Context) *RequestWithContext 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) errorWrite 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 [Request.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) errorWriteProxy is like Request.Write but writes the request in the form expected by an HTTP proxy. In particular, Request.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() []*CookieCookies 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 [Response.Request]. ErrNoLocation is returned if no Location header is present.
func ProtoAtLeast
1func (r *Response) ProtoAtLeast(major, minor int) boolProtoAtLeast reports whether the HTTP protocol used in the response is at least major.minor.
func Write
1func (r *Response) Write(w io.Writer) errorWrite 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 // [ResponseWriter.WriteHeader]. The [Header] map also is the mechanism with which
4 // [Handler] implementations can set HTTP trailers.
5 //
6 // Changing the header map after a call to [ResponseWriter.WriteHeader] (or
7 // [ResponseWriter.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 [ResponseWriter.Write],
17 // is to prefix the [Header] map keys with the [TrailerPrefix]
18 // constant value.
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 [ResponseWriter.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 [Handler.ServeHTTP] 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
Patterns can match the method, host and path of a request. Some examples:
- “/index.html” matches the path “/index.html” for any host and method.
- “GET /static/” matches a GET request whose path begins with “/static/”.
- “example.com/” matches any request to the host “example.com”.
- “example.com/{$}” matches requests with host “example.com” and path “/”.
- “/b/{bucket}/o/{objectname…}” matches paths whose first segment is “b” and whose third segment is “o”. The name “bucket” denotes the second segment and “objectname” denotes the remainder of the path.
In general, a pattern looks like
[METHOD ][HOST]/[PATH]
All three parts are optional; “/” is a valid pattern. If METHOD is present, it must be followed by at least one space or tab.
Literal (that is, non-wildcard) parts of a pattern match the corresponding parts of a request case-sensitively.
A pattern with no method matches every method. A pattern with the method GET matches both GET and HEAD requests. Otherwise, the method must match exactly.
A pattern with no host matches every host. A pattern with a host matches URLs on that host only.
A path can include wildcard segments of the form {NAME} or {NAME…}. For example, “/b/{bucket}/o/{objectname…}”. The wildcard name must be a valid Go identifier. Wildcards must be full path segments: they must be preceded by a slash and followed by either a slash or the end of the string. For example, “/b_{bucket}” is not a valid pattern.
Normally a wildcard matches only a single path segment, ending at the next literal slash (not %2F) in the request URL. But if the “…” is present, then the wildcard matches the remainder of the URL path, including slashes. (Therefore it is invalid for a “…” wildcard to appear anywhere but at the end of a pattern.) The match for a wildcard can be obtained by calling Request.PathValue with the wildcard’s name. A trailing slash in a path acts as an anonymous “…” wildcard.
The special wildcard {$} matches only the end of the URL. For example, the pattern “/{$}” matches only the path “/”, whereas the pattern “/” matches every path.
For matching, both pattern paths and incoming request paths are unescaped segment by segment. So, for example, the path “/a%2Fb/100%25” is treated as having two segments, “a/b” and “100%”. The pattern “/a%2fb/” matches it, but the pattern “/a/b/” does not.
Precedence
If two or more patterns match a request, then the most specific pattern takes precedence. A pattern P1 is more specific than P2 if P1 matches a strict subset of P2’s requests; that is, if P2 matches all the requests of P1 and more. If neither is more specific, then the patterns conflict. There is one exception to this rule, for backwards compatibility: if two patterns would otherwise conflict and one has a host while the other does not, then the pattern with the host takes precedence. If a pattern passed to ServeMux.Handle or ServeMux.HandleFunc conflicts with another pattern that is already registered, those functions panic.
As an example of the general rule, “/images/thumbnails/” is more specific than “/images/”, so both can be registered. The former matches paths beginning with “/images/thumbnails/” and the latter will match any other path in the “/images/” subtree.
As another example, consider the patterns “GET /” and “/index.html”: both match a GET request for “/index.html”, but the former pattern matches all other GET and HEAD requests, while the latter matches any request for “/index.html” that uses a different method. The patterns conflict.
Trailing-slash redirection
Consider a ServeMux with a handler for a subtree, registered using a trailing slash or “…” wildcard. If the ServeMux receives a request for the subtree root without a trailing slash, it redirects the request by adding the trailing slash. This behavior can be overridden with a separate registration for the path without the trailing slash or “…” wildcard. For example, registering “/images/” causes ServeMux to redirect a request for “/images” to “/images/”, unless “/images” has been registered separately.
Request sanitizing
ServeMux also takes care of sanitizing the URL request path and the Host header, stripping the port number and redirecting any request containing . or .. segments or repeated slashes to an equivalent, cleaner URL.
Compatibility
The pattern syntax and matching behavior of ServeMux changed significantly in Go 1.22. To restore the old behavior, set the GODEBUG environment variable to “httpmuxgo121=1”. This setting is read once, at program startup; changes during execution will be ignored.
The backwards-incompatible changes include:
- Wildcards are just ordinary literal path segments in 1.21. For example, the pattern “/{x}” will match only that path in 1.21, but will match any one-segment path in 1.22.
- In 1.21, no pattern was rejected, unless it was empty or conflicted with an existing pattern. In 1.22, syntactically invalid patterns will cause ServeMux.Handle and ServeMux.HandleFunc to panic. For example, in 1.21, the patterns “/{” and “/a{x}” match themselves, but in 1.22 they are invalid and will cause a panic when registered.
- In 1.22, each segment of a pattern is unescaped; this was not done in 1.21. For example, in 1.22 the pattern “/%61” matches the path “/a” ("%61" being the URL escape sequence for “a”), but in 1.21 it would match only the path “/%2561” (where “%25” is the escape for the percent sign).
- When matching patterns to paths, in 1.22 each segment of the path is unescaped; in 1.21, the entire path is unescaped. This change mostly affects how paths with %2F escapes adjacent to slashes are treated. See https://go.dev/issue/21955 for details.
func Handle
1func (mux *ServeMux) Handle(pattern string, handler Handler)Handle registers the handler for the given pattern. If the given pattern conflicts, with one that is already registered, 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. If the given pattern conflicts, with one that is already registered, HandleFunc panics.
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 path 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.
type Transport
1type Transport struct {
2
3 // Proxy specifies a function to return a proxy for a given
4 // Request. If the function returns a non-nil error, the
5 // request is aborted with the provided error.
6 //
7 // The proxy type is determined by the URL scheme. "http",
8 // "https", "socks5", and "socks5h" are supported. If the scheme is empty,
9 // "http" is assumed.
10 // "socks5" is treated the same as "socks5h".
11 //
12 // If the proxy URL contains a userinfo subcomponent,
13 // the proxy request will pass the username and password
14 // in a Proxy-Authorization header.
15 //
16 // If Proxy is nil or returns a nil *URL, no proxy is used.
17 Proxy func(*Request) (*url.URL, error)
18
19 // OnProxyConnectResponse is called when the Transport gets an HTTP response from
20 // a proxy for a CONNECT request. It's called before the check for a 200 OK response.
21 // If it returns an error, the request fails with that error.
22 OnProxyConnectResponse func(ctx context.Context, proxyURL *url.URL, connectReq *Request, connectRes *Response) error
23
24 // DialContext specifies the dial function for creating unencrypted TCP connections.
25 // If DialContext is nil (and the deprecated Dial below is also nil),
26 // then the transport dials using package net.
27 //
28 // DialContext runs concurrently with calls to RoundTrip.
29 // A RoundTrip call that initiates a dial may end up using
30 // a connection dialed previously when the earlier connection
31 // becomes idle before the later DialContext completes.
32 DialContext func(ctx context.Context, network, addr string) (net.Conn, error)
33
34 // Dial specifies the dial function for creating unencrypted TCP connections.
35 //
36 // Dial runs concurrently with calls to RoundTrip.
37 // A RoundTrip call that initiates a dial may end up using
38 // a connection dialed previously when the earlier connection
39 // becomes idle before the later Dial completes.
40 //
41 // Deprecated: Use DialContext instead, which allows the transport
42 // to cancel dials as soon as they are no longer needed.
43 // If both are set, DialContext takes priority.
44 Dial func(network, addr string) (net.Conn, error)
45
46 // DialTLSContext specifies an optional dial function for creating
47 // TLS connections for non-proxied HTTPS requests.
48 //
49 // If DialTLSContext is nil (and the deprecated DialTLS below is also nil),
50 // DialContext and TLSClientConfig are used.
51 //
52 // If DialTLSContext is set, the Dial and DialContext hooks are not used for HTTPS
53 // requests and the TLSClientConfig and TLSHandshakeTimeout
54 // are ignored. The returned net.Conn is assumed to already be
55 // past the TLS handshake.
56 DialTLSContext func(ctx context.Context, network, addr string) (net.Conn, error)
57
58 // DialTLS specifies an optional dial function for creating
59 // TLS connections for non-proxied HTTPS requests.
60 //
61 // Deprecated: Use DialTLSContext instead, which allows the transport
62 // to cancel dials as soon as they are no longer needed.
63 // If both are set, DialTLSContext takes priority.
64 DialTLS func(network, addr string) (net.Conn, error)
65
66 // TLSClientConfig specifies the TLS configuration to use with
67 // tls.Client.
68 // If nil, the default configuration is used.
69 // If non-nil, HTTP/2 support may not be enabled by default.
70 TLSClientConfig *tls.Config
71
72 // TLSHandshakeTimeout specifies the maximum amount of time to
73 // wait for a TLS handshake. Zero means no timeout.
74 TLSHandshakeTimeout time.Duration
75
76 // DisableKeepAlives, if true, disables HTTP keep-alives and
77 // will only use the connection to the server for a single
78 // HTTP request.
79 //
80 // This is unrelated to the similarly named TCP keep-alives.
81 DisableKeepAlives bool
82
83 // DisableCompression, if true, prevents the Transport from
84 // requesting compression with an "Accept-Encoding: gzip"
85 // request header when the Request contains no existing
86 // Accept-Encoding value. If the Transport requests gzip on
87 // its own and gets a gzipped response, it's transparently
88 // decoded in the Response.Body. However, if the user
89 // explicitly requested gzip it is not automatically
90 // uncompressed.
91 DisableCompression bool
92
93 // MaxIdleConns controls the maximum number of idle (keep-alive)
94 // connections across all hosts. Zero means no limit.
95 MaxIdleConns int
96
97 // MaxIdleConnsPerHost, if non-zero, controls the maximum idle
98 // (keep-alive) connections to keep per-host. If zero,
99 // DefaultMaxIdleConnsPerHost is used.
100 MaxIdleConnsPerHost int
101
102 // MaxConnsPerHost optionally limits the total number of
103 // connections per host, including connections in the dialing,
104 // active, and idle states. On limit violation, dials will block.
105 //
106 // Zero means no limit.
107 MaxConnsPerHost int
108
109 // IdleConnTimeout is the maximum amount of time an idle
110 // (keep-alive) connection will remain idle before closing
111 // itself.
112 // Zero means no limit.
113 IdleConnTimeout time.Duration
114
115 // ResponseHeaderTimeout, if non-zero, specifies the amount of
116 // time to wait for a server's response headers after fully
117 // writing the request (including its body, if any). This
118 // time does not include the time to read the response body.
119 ResponseHeaderTimeout time.Duration
120
121 // ExpectContinueTimeout, if non-zero, specifies the amount of
122 // time to wait for a server's first response headers after fully
123 // writing the request headers if the request has an
124 // "Expect: 100-continue" header. Zero means no timeout and
125 // causes the body to be sent immediately, without
126 // waiting for the server to approve.
127 // This time does not include the time to send the request header.
128 ExpectContinueTimeout time.Duration
129
130 // TLSNextProto specifies how the Transport switches to an
131 // alternate protocol (such as HTTP/2) after a TLS ALPN
132 // protocol negotiation. If Transport dials a TLS connection
133 // with a non-empty protocol name and TLSNextProto contains a
134 // map entry for that key (such as "h2"), then the func is
135 // called with the request's authority (such as "example.com"
136 // or "example.com:1234") and the TLS connection. The function
137 // must return a RoundTripper that then handles the request.
138 // If TLSNextProto is not nil, HTTP/2 support is not enabled
139 // automatically.
140 TLSNextProto map[string]func(authority string, c *tls.Conn) RoundTripper
141
142 // ProxyConnectHeader optionally specifies headers to send to
143 // proxies during CONNECT requests.
144 // To set the header dynamically, see GetProxyConnectHeader.
145 ProxyConnectHeader Header
146
147 // GetProxyConnectHeader optionally specifies a func to return
148 // headers to send to proxyURL during a CONNECT request to the
149 // ip:port target.
150 // If it returns an error, the Transport's RoundTrip fails with
151 // that error. It can return (nil, nil) to not add headers.
152 // If GetProxyConnectHeader is non-nil, ProxyConnectHeader is
153 // ignored.
154 GetProxyConnectHeader func(ctx context.Context, proxyURL *url.URL, target string) (Header, error)
155
156 // MaxResponseHeaderBytes specifies a limit on how many
157 // response bytes are allowed in the server's response
158 // header.
159 //
160 // Zero means to use a default limit.
161 MaxResponseHeaderBytes int64
162
163 // WriteBufferSize specifies the size of the write buffer used
164 // when writing to the transport.
165 // If zero, a default (currently 4KB) is used.
166 WriteBufferSize int
167
168 // ReadBufferSize specifies the size of the read buffer used
169 // when reading from the transport.
170 // If zero, a default (currently 4KB) is used.
171 ReadBufferSize int
172
173 // ForceAttemptHTTP2 controls whether HTTP/2 is enabled when a non-zero
174 // Dial, DialTLS, or DialContext func or TLSClientConfig is provided.
175 // By default, use of any those fields conservatively disables HTTP/2.
176 // To use a custom dialer or TLS config and still attempt HTTP/2
177 // upgrades, set this to true.
178 ForceAttemptHTTP2 bool
179}Transport is an implementation of RoundTripper that supports HTTP, HTTPS, and HTTP proxies (for either HTTP or HTTPS with CONNECT).
By default, Transport caches connections for future re-use. This may leave many open connections when accessing many hosts. This behavior can be managed using Transport.CloseIdleConnections method and the [Transport.MaxIdleConnsPerHost] and [Transport.DisableKeepAlives] fields.
Transports should be reused instead of created as needed. Transports are safe for concurrent use by multiple goroutines.
A Transport is a low-level primitive for making HTTP and HTTPS requests. For high-level functionality, such as cookies and redirects, see Client.
Transport uses HTTP/1.1 for HTTP URLs and either HTTP/1.1 or HTTP/2 for HTTPS URLs, depending on whether the server supports HTTP/2, and how the Transport is configured. The DefaultTransport supports HTTP/2. To explicitly enable HTTP/2 on a transport, use golang.org/x/net/http2 and call ConfigureTransport. See the package docs for more about HTTP/2.
Responses with status codes in the 1xx range are either handled automatically (100 expect-continue) or ignored. The one exception is HTTP status code 101 (Switching Protocols), which is considered a terminal status and returned by Transport.RoundTrip. To see the ignored 1xx responses, use the httptrace trace package’s ClientTrace.Got1xxResponse.
Transport only retries a request upon encountering a network error if the connection has been already been used successfully and if the request is idempotent and either has no body or has its [Request.GetBody] defined. HTTP requests are considered idempotent if they have HTTP methods GET, HEAD, OPTIONS, or TRACE; or if their Header map contains an “Idempotency-Key” or “X-Idempotency-Key” entry. If the idempotency key value is a zero-length slice, the request is treated as idempotent but the header is not sent on the wire.
func CancelRequest
1func (t *Transport) CancelRequest(req *Request)CancelRequest cancels an in-flight request by closing its connection. CancelRequest should only be called after Transport.RoundTrip has returned.
Deprecated: Use Request.WithContext to create a request with a cancelable context instead. CancelRequest cannot cancel HTTP/2 requests. This may become a no-op in a future release of Go.
func Clone
1func (t *Transport) Clone() *TransportClone returns a deep copy of t's exported fields.
func CloseIdleConnections
1func (t *Transport) CloseIdleConnections()CloseIdleConnections closes any connections 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.
func RegisterProtocol
1func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper)RegisterProtocol registers a new protocol with scheme. The Transport will pass requests using the given scheme to rt. It is rt's responsibility to simulate HTTP request semantics.
RegisterProtocol can be used by other packages to provide implementations of protocol schemes like “ftp” or “file”.
If rt.RoundTrip returns ErrSkipAltProtocol, the Transport will handle the Transport.RoundTrip itself for that one request, as if the protocol were not registered.
func RoundTrip
1func (t *Transport) RoundTrip(req *Request) (*Response, error)RoundTrip implements the RoundTripper interface.
For higher-level HTTP client support (such as handling of cookies and redirects), see Get, Post, and the Client type.
Like the RoundTripper interface, the error types returned by RoundTrip are unspecified.