type Client(struct)
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.
CheckRedirectfunc(req *Request, via []*Request) errorJarCookieJarTimeouttime.DurationTransportRoundTripper
(*T) CloseIdleConnections()
(*T) Do(req *Request) (*Response, error)
(*T) Get(url string) (resp *Response, err error)
(*T) Head(url string) (resp *Response, err error)
(*T) Post(url, contentType string, body io.Reader) (resp *Response, err error)
(*T) PostForm(url string, data url.Values) (resp *Response, err error)
var DefaultClient *Client
type CloseNotifier(interface)
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.
(T) CloseNotify() <-chan bool
type CookieJar(interface)
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.
(T) Cookies(u *url.URL) []*Cookie
(T) SetCookies(u *url.URL, cookies []*Cookie)
type Dirstring
A Dir implements FileSystem using the native file system restricted to a
specific directory tree.
While the FileSystem.Open method takes '/'-separated paths, a Dir's string
value is a filename on the native file system, not a URL, so it is separated
by filepath.Separator, which isn't necessarily '/'.
Note that Dir could expose sensitive files and directories. Dir will follow
symlinks pointing out of the directory tree, which can be especially dangerous
if serving from a directory in which users are able to create arbitrary symlinks.
Dir will also allow access to files and directories starting with a period,
which could expose sensitive directories like .git or sensitive files like
.htpasswd. To exclude files with a leading period, remove the files/directories
from the server or create a custom FileSystem implementation.
An empty Dir is treated as ".".
(T) Open(name string) (File, error)
T : FileSystem
type FileSystem(interface)
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.
(T) Open(name string) (File, error)Dir
func FileServer(root FileSystem) Handler
func NewFileTransport(fs FileSystem) RoundTripper
type Flusher(interface)
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.
(T) Flush()
type Handler(interface)
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.
(T) ServeHTTP(ResponseWriter, *Request)HandlerFunc
*ServeMux
github.com/gorilla/mux.(*Router)
func FileServer(root FileSystem) Handler
func NotFoundHandler() Handler
func RedirectHandler(url string, code int) Handler
func StripPrefix(prefix string, h Handler) Handler
func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler
func (*ServeMux).Handler(r *Request) (h Handler, pattern string)
func github.com/gorilla/mux.MiddlewareFunc.Middleware(handler Handler) Handler
func github.com/gorilla/mux.(*Route).GetHandler() Handler
func Handle(pattern string, handler Handler)
func ListenAndServe(addr string, handler Handler) error
func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error
func Serve(l net.Listener, handler Handler) error
func ServeTLS(l net.Listener, handler Handler, certFile, keyFile string) error
func StripPrefix(prefix string, h Handler) Handler
func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler
func (*ServeMux).Handle(pattern string, handler Handler)
func github.com/gorilla/mux.MiddlewareFunc.Middleware(handler Handler) Handler
func github.com/gorilla/mux.(*Route).Handler(handler Handler) *mux.Route
func github.com/gorilla/mux.(*Router).Handle(path string, handler Handler) *mux.Route
type HandlerFunc(func)
The HandlerFunc type is an adapter to allow the use of
ordinary functions as HTTP handlers. If f is a function
with the appropriate signature, HandlerFunc(f) is a
Handler that calls f.
(T) ServeHTTP(w ResponseWriter, r *Request)
T : Handler
type Hijacker(interface)
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.
(T) Hijack() (net.Conn, *bufio.ReadWriter, error)
type Pusher(interface)
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.
(T) Push(target string, opts *PushOptions) error
type SameSiteint
SameSite allows a server to define a cookie attribute making it impossible for
the browser to send this cookie along with cross-site requests. The main
goal is to mitigate the risk of cross-origin information leakage, and provide
some protection against cross-site request forgery attacks.
See https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00 for details.
const SameSiteDefaultMode
const SameSiteLaxMode
const SameSiteNoneMode
const SameSiteStrictMode
type ServeMux(struct)
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.
(*T) Handle(pattern string, handler Handler)
(*T) HandleFunc(pattern string, handler func(ResponseWriter, *Request))
(*T) Handler(r *Request) (h Handler, pattern string)
(*T) ServeHTTP(w ResponseWriter, r *Request)
*T : Handler
func NewServeMux() *ServeMux
var DefaultServeMux *ServeMux
type Transport(struct)
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's CloseIdleConnections method
and the MaxIdleConnsPerHost and 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 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 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.
Dialfunc(network, addr string) (net.Conn, error)DialContextfunc(ctx context.Context, network, addr string) (net.Conn, error)DialTLSfunc(network, addr string) (net.Conn, error)DialTLSContextfunc(ctx context.Context, network, addr string) (net.Conn, error)DisableCompressionboolDisableKeepAlivesboolExpectContinueTimeouttime.DurationForceAttemptHTTP2boolIdleConnTimeouttime.DurationMaxConnsPerHostintMaxIdleConnsintMaxIdleConnsPerHostintMaxResponseHeaderBytesint64Proxyfunc(*Request) (*url.URL, error)ProxyConnectHeaderHeaderReadBufferSizeintResponseHeaderTimeouttime.DurationTLSClientConfig*tls.ConfigTLSHandshakeTimeouttime.DurationTLSNextProtomap[string]func(authority string, c *tls.Conn) RoundTripperWriteBufferSizeint
(*T) CancelRequest(req *Request)
(*T) Clone() *Transport
(*T) CloseIdleConnections()
(*T) RegisterProtocol(scheme string, rt RoundTripper)
(*T) RoundTrip(req *Request) (*Response, error)
*T : RoundTripper
func (*Transport).Clone() *Transport
Exported Values
func CanonicalHeaderKey(s string) string
CanonicalHeaderKey returns the canonical format of the
header key s. The canonicalization converts the first
letter and any letter following a hyphen to upper case;
the rest are converted to lowercase. For example, the
canonical key for "accept-encoding" is "Accept-Encoding".
If s contains a space or invalid header field bytes, it is
returned without modifications.
var DefaultClient *Client
DefaultClient is the default Client and is used by Get, Head, and Post.
const DefaultMaxHeaderBytes = 1048576 // 1 MB
DefaultMaxHeaderBytes is the maximum permitted size of the headers
in an HTTP request.
This can be overridden by setting Server.MaxHeaderBytes.
const DefaultMaxIdleConnsPerHost = 2
DefaultMaxIdleConnsPerHost is the default value of Transport's
MaxIdleConnsPerHost.
var DefaultTransportRoundTripper
DefaultTransport is the default implementation of Transport and is
used by DefaultClient. It establishes network connections as needed
and caches them for reuse by subsequent calls. It uses HTTP proxies
as directed by the $HTTP_PROXY and $NO_PROXY (or $http_proxy and
$no_proxy) environment variables.
func DetectContentType(data []byte) string
DetectContentType implements the algorithm described
at https://mimesniff.spec.whatwg.org/ to determine the
Content-Type of the given data. It considers at most the
first 512 bytes of data. DetectContentType always returns
a valid MIME type: if it cannot determine a more specific one, it
returns "application/octet-stream".
var ErrAbortHandlererror
ErrAbortHandler is a sentinel panic value to abort a handler.
While any panic from ServeHTTP aborts the response to the client,
panicking with ErrAbortHandler also suppresses logging of a stack
trace to the server's error log.
var ErrBodyNotAllowederror
ErrBodyNotAllowed is returned by ResponseWriter.Write calls
when the HTTP method or response code does not permit a
body.
var ErrBodyReadAfterCloseerror
ErrBodyReadAfterClose is returned when reading a Request or Response
Body after the body has been closed. This typically happens when the body is
read after an HTTP Handler calls WriteHeader or Write on its
ResponseWriter.
var ErrContentLengtherror
ErrContentLength is returned by ResponseWriter.Write calls
when a Handler set a Content-Length response header with a
declared size and then attempted to write more bytes than
declared.
var ErrHandlerTimeouterror
ErrHandlerTimeout is returned on ResponseWriter Write calls
in handlers which have timed out.
var ErrHeaderTooLong *ProtocolError
Deprecated: ErrHeaderTooLong is no longer returned by
anything in the net/http package. Callers should not
compare errors against this variable.
var ErrHijackederror
ErrHijacked is returned by ResponseWriter.Write calls when
the underlying connection has been hijacked using the
Hijacker interface. A zero-byte write on a hijacked
connection will return ErrHijacked without any other side
effects.
var ErrLineTooLongerror
ErrLineTooLong is returned when reading request or response bodies
with malformed chunked encoding.
var ErrMissingBoundary *ProtocolError
ErrMissingBoundary is returned by Request.MultipartReader when the
request's Content-Type does not include a "boundary" parameter.
var ErrMissingContentLength *ProtocolError
Deprecated: ErrMissingContentLength is no longer returned by
anything in the net/http package. Callers should not
compare errors against this variable.
var ErrMissingFileerror
ErrMissingFile is returned by FormFile when the provided file field name
is either not present in the request or not a file field.
var ErrNoCookieerror
ErrNoCookie is returned by Request's Cookie method when a cookie is not found.
var ErrNoLocationerror
ErrNoLocation is returned by Response's Location method
when no Location header is present.
var ErrNotMultipart *ProtocolError
ErrNotMultipart is returned by Request.MultipartReader when the
request's Content-Type is not multipart/form-data.
var ErrNotSupported *ProtocolError
ErrNotSupported is returned by the Push method of Pusher
implementations to indicate that HTTP/2 Push support is not
available.
func Error(w ResponseWriter, error string, code int)
Error replies to the request with the specified error message and HTTP code.
It does not otherwise end the request; the caller should ensure no further
writes are done to w.
The error message should be plain text.
var ErrServerClosederror
ErrServerClosed is returned by the Server's Serve, ServeTLS, ListenAndServe,
and ListenAndServeTLS methods after a call to Shutdown or Close.
var ErrShortBody *ProtocolError
Deprecated: ErrShortBody is no longer returned by
anything in the net/http package. Callers should not
compare errors against this variable.
var ErrSkipAltProtocolerror
ErrSkipAltProtocol is a sentinel error value defined by Transport.RegisterProtocol.
var ErrUnexpectedTrailer *ProtocolError
Deprecated: ErrUnexpectedTrailer is no longer returned by
anything in the net/http package. Callers should not
compare errors against this variable.
var ErrUseLastResponseerror
ErrUseLastResponse can be returned by Client.CheckRedirect hooks to
control how redirects are processed. If returned, the next request
is not sent and the most recent response is returned with its body
unclosed.
var ErrWriteAfterFlusherror
Deprecated: ErrWriteAfterFlush is no longer returned by
anything in the net/http package. Callers should not
compare errors against this variable.
func FileServer(root FileSystem) Handler
FileServer returns a handler that serves HTTP requests
with the contents of the file system rooted at root.
To use the operating system's file system implementation,
use http.Dir:
http.Handle("/", http.FileServer(http.Dir("/tmp")))
As a special case, the returned file server redirects any request
ending in "/index.html" to the same path, without the final
"index.html".
func 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, up to a
maximum of 10 redirects:
301 (Moved Permanently)
302 (Found)
303 (See Other)
307 (Temporary Redirect)
308 (Permanent Redirect)
An error is returned if there were too many redirects 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 request timed out or was
canceled.
When err is nil, resp always contains a non-nil resp.Body.
Caller should close resp.Body when done reading from it.
Get is a wrapper around DefaultClient.Get.
To make a request with custom headers, use NewRequest and
DefaultClient.Do.
func 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.
func 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.
func 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, up to a
maximum of 10 redirects:
301 (Moved Permanently)
302 (Found)
303 (See Other)
307 (Temporary Redirect)
308 (Permanent Redirect)
Head is a wrapper around DefaultClient.Head
func 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.
func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error
ListenAndServeTLS acts identically to ListenAndServe, except that it
expects HTTPS connections. Additionally, files containing a certificate and
matching private key for the server must be provided. If the certificate
is signed by a certificate authority, the certFile should be the concatenation
of the server's certificate, any intermediates, and the CA's certificate.
var LocalAddrContextKey *contextKey
LocalAddrContextKey is a context key. It can be used in
HTTP handlers with Context.Value to access the local
address the connection arrived on.
The associated value will be of type net.Addr.
func MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser
MaxBytesReader is similar to io.LimitReader but is intended for
limiting the size of incoming request bodies. In contrast to
io.LimitReader, MaxBytesReader's result is a ReadCloser, returns a
non-EOF error for a Read beyond the limit, and closes the
underlying reader when its Close method is called.
MaxBytesReader prevents clients from accidentally or maliciously
sending a large request and wasting server resources.
const MethodConnect = "CONNECT"
Common HTTP methods.
Unless otherwise noted, these are defined in RFC 7231 section 4.3.
const MethodDelete = "DELETE"
Common HTTP methods.
Unless otherwise noted, these are defined in RFC 7231 section 4.3.
const MethodGet = "GET"
Common HTTP methods.
Unless otherwise noted, these are defined in RFC 7231 section 4.3.
const MethodHead = "HEAD"
Common HTTP methods.
Unless otherwise noted, these are defined in RFC 7231 section 4.3.
const MethodOptions = "OPTIONS"
Common HTTP methods.
Unless otherwise noted, these are defined in RFC 7231 section 4.3.
const MethodPatch = "PATCH" // RFC 5789
Common HTTP methods.
Unless otherwise noted, these are defined in RFC 7231 section 4.3.
const MethodPost = "POST"
Common HTTP methods.
Unless otherwise noted, these are defined in RFC 7231 section 4.3.
const MethodPut = "PUT"
Common HTTP methods.
Unless otherwise noted, these are defined in RFC 7231 section 4.3.
const MethodTrace = "TRACE"
Common HTTP methods.
Unless otherwise noted, these are defined in RFC 7231 section 4.3.
func NewFileTransport(fs FileSystem) RoundTripper
NewFileTransport returns a new RoundTripper, serving the provided
FileSystem. The returned RoundTripper ignores the URL host in its
incoming requests, as well as most other properties of the
request.
The typical use case for NewFileTransport is to register the "file"
protocol with a Transport, as in:
t := &http.Transport{}
t.RegisterProtocol("file", http.NewFileTransport(http.Dir("/")))
c := &http.Client{Transport: t}
res, err := c.Get("file:///etc/passwd")
...
func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error)
NewRequestWithContext returns a new Request given a method, URL, and
optional body.
If the provided body is also an io.Closer, the returned
Request.Body is set to body and will be closed by the Client
methods Do, Post, and PostForm, and Transport.RoundTrip.
NewRequestWithContext returns a Request suitable for use with
Client.Do or Transport.RoundTrip. To create a request for use with
testing a Server Handler, either use the NewRequest function in the
net/http/httptest package, use ReadRequest, or manually update the
Request fields. 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. See the Request type's documentation for
the difference between inbound and outbound request fields.
If body is of type *bytes.Buffer, *bytes.Reader, or
*strings.Reader, the returned request's ContentLength is set to its
exact value (instead of -1), GetBody is populated (so 307 and 308
redirects can replay the body), and Body is set to NoBody if the
ContentLength is 0.
func NewServeMux() *ServeMux
NewServeMux allocates and returns a new ServeMux.
var NoBodynoBody
NoBody is an io.ReadCloser with no bytes. Read always returns EOF
and Close always returns nil. It can be used in an outgoing client
request to explicitly signal that a request has zero bytes.
An alternative, however, is to simply set Request.Body to nil.
func NotFoundHandler() Handler
NotFoundHandler returns a simple request handler
that replies to each request with a ``404 page not found'' reply.
func ParseHTTPVersion(vers string) (major, minor int, ok bool)
ParseHTTPVersion parses an HTTP version string.
"HTTP/1.0" returns (1, 0, true).
func ParseTime(text string) (t time.Time, err error)
ParseTime parses a time header (such as the Date: header),
trying each of the three formats allowed by HTTP/1.1:
TimeFormat, time.RFC850, and time.ANSIC.
func 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.
Post is a wrapper around DefaultClient.Post.
To set custom headers, use NewRequest and DefaultClient.Do.
See the Client.Do method documentation for details on how redirects
are handled.
func 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.
func ProxyFromEnvironment(req *Request) (*url.URL, error)
ProxyFromEnvironment returns the URL of the proxy to use for a
given request, as indicated by the environment variables
HTTP_PROXY, HTTPS_PROXY and NO_PROXY (or the lowercase versions
thereof). HTTPS_PROXY takes precedence over HTTP_PROXY for https
requests.
The environment values may be either a complete URL or a
"host[:port]", in which case the "http" scheme is assumed.
An error is returned if the value is a different form.
A nil URL and nil error are returned if no proxy is defined in the
environment, or a proxy should not be used for the given request,
as defined by NO_PROXY.
As a special case, if req.URL.Host is "localhost" (with or without
a port number), then a nil URL and nil error will be returned.
func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error)
ProxyURL returns a proxy function (for use in a Transport)
that always returns the same URL.
func ReadRequest(b *bufio.Reader) (*Request, error)
ReadRequest reads and parses an incoming request from b.
ReadRequest is a low-level function and should only be used for
specialized applications; most code should use the Server to read
requests and handle them via the Handler interface. ReadRequest
only supports HTTP/1.x requests. For HTTP/2, use golang.org/x/net/http2.
func ReadResponse(r *bufio.Reader, req *Request) (*Response, error)
ReadResponse reads and returns an HTTP response from r.
The req parameter optionally specifies the Request that corresponds
to this Response. If nil, a GET request is assumed.
Clients must call resp.Body.Close when finished reading resp.Body.
After that call, clients can inspect resp.Trailer to find key/value
pairs included in the response trailer.
func Redirect(w ResponseWriter, r *Request, url string, code int)
Redirect replies to the request with a redirect to url,
which may be a path relative to the request path.
The provided code should be in the 3xx range and is usually
StatusMovedPermanently, StatusFound or StatusSeeOther.
If the Content-Type header has not been set, Redirect sets it
to "text/html; charset=utf-8" and writes a small HTML body.
Setting the Content-Type header to any value, including nil,
disables that behavior.
func RedirectHandler(url string, code int) Handler
RedirectHandler returns a request handler that redirects
each request it receives to the given url using the given
status code.
The provided code should be in the 3xx range and is usually
StatusMovedPermanently, StatusFound or StatusSeeOther.
func 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 ServeContent(w ResponseWriter, req *Request, name string, modtime time.Time, content io.ReadSeeker)
ServeContent replies to the request using the content in the
provided ReadSeeker. The main benefit of ServeContent over io.Copy
is that it handles Range requests properly, sets the MIME type, and
handles If-Match, If-Unmodified-Since, If-None-Match, If-Modified-Since,
and If-Range requests.
If the response's Content-Type header is not set, ServeContent
first tries to deduce the type from name's file extension and,
if that fails, falls back to reading the first block of the content
and passing it to DetectContentType.
The name is otherwise unused; in particular it can be empty and is
never sent in the response.
If modtime is not the zero time or Unix epoch, ServeContent
includes it in a Last-Modified header in the response. If the
request includes an If-Modified-Since header, ServeContent uses
modtime to decide whether the content needs to be sent at all.
The content's Seek method must work: ServeContent uses
a seek to the end of the content to determine its size.
If the caller has set w's ETag header formatted per RFC 7232, section 2.3,
ServeContent uses it to handle requests using If-Match, If-None-Match, or If-Range.
Note that *os.File implements the io.ReadSeeker interface.
func ServeFile(w ResponseWriter, r *Request, name string)
ServeFile replies to the request with the contents of the named
file or directory.
If the provided file or directory name is a relative path, it is
interpreted relative to the current directory and may ascend to
parent directories. If the provided name is constructed from user
input, it should be sanitized before calling ServeFile.
As a precaution, ServeFile will reject requests where r.URL.Path
contains a ".." path element; this protects against callers who
might unsafely use filepath.Join on r.URL.Path without sanitizing
it and then use that filepath.Join result as the name argument.
As another special case, ServeFile redirects any request where r.URL.Path
ends in "/index.html" to the same path, without the final
"index.html". To avoid such redirects either modify the path or
use ServeContent.
Outside of those two special cases, ServeFile does not use
r.URL.Path for selecting the file or directory to serve; only the
file or directory provided in the name argument is used.
var ServerContextKey *contextKey
ServerContextKey is a context key. It can be used in HTTP
handlers with Context.Value to access the server that
started the handler. The associated value will be of
type *Server.
func ServeTLS(l net.Listener, handler Handler, certFile, keyFile string) error
ServeTLS accepts incoming HTTPS 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.
Additionally, files containing a certificate and matching private key
for the server must be provided. If the certificate is signed by a
certificate authority, the certFile should be the concatenation
of the server's certificate, any intermediates, and the CA's certificate.
ServeTLS always returns a non-nil error.
func 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.
const StateActiveConnState = 1
StateActive represents a connection that has read 1 or more
bytes of a request. The Server.ConnState hook for
StateActive fires before the request has entered a handler
and doesn't fire again until the request has been
handled. After the request is handled, the state
transitions to StateClosed, StateHijacked, or StateIdle.
For HTTP/2, StateActive fires on the transition from zero
to one active request, and only transitions away once all
active requests are complete. That means that ConnState
cannot be used to do per-request work; ConnState only notes
the overall state of the connection.
const StateClosedConnState = 4
StateClosed represents a closed connection.
This is a terminal state. Hijacked connections do not
transition to StateClosed.
const StateHijackedConnState = 3
StateHijacked represents a hijacked connection.
This is a terminal state. It does not transition to StateClosed.
const StateIdleConnState = 2
StateIdle represents a connection that has finished
handling a request and is in the keep-alive state, waiting
for a new request. Connections transition from StateIdle
to either StateActive or StateClosed.
const StateNewConnState = 0
StateNew represents a new connection that is expected to
send a request immediately. Connections begin at this
state and then transition to either StateActive or
StateClosed.
const StatusAccepted = 202 // RFC 7231, 6.3.3
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusAlreadyReported = 208 // RFC 5842, 7.1
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusBadGateway = 502 // RFC 7231, 6.6.3
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusBadRequest = 400 // RFC 7231, 6.5.1
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusConflict = 409 // RFC 7231, 6.5.8
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusContinue = 100 // RFC 7231, 6.2.1
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusCreated = 201 // RFC 7231, 6.3.2
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusEarlyHints = 103 // RFC 8297
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusExpectationFailed = 417 // RFC 7231, 6.5.14
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusFailedDependency = 424 // RFC 4918, 11.4
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusForbidden = 403 // RFC 7231, 6.5.3
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusFound = 302 // RFC 7231, 6.4.3
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusGatewayTimeout = 504 // RFC 7231, 6.6.5
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusGone = 410 // RFC 7231, 6.5.9
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusHTTPVersionNotSupported = 505 // RFC 7231, 6.6.6
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusIMUsed = 226 // RFC 3229, 10.4.1
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusInsufficientStorage = 507 // RFC 4918, 11.5
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusInternalServerError = 500 // RFC 7231, 6.6.1
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusLengthRequired = 411 // RFC 7231, 6.5.10
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusLocked = 423 // RFC 4918, 11.3
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusLoopDetected = 508 // RFC 5842, 7.2
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusMethodNotAllowed = 405 // RFC 7231, 6.5.5
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusMisdirectedRequest = 421 // RFC 7540, 9.1.2
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusMovedPermanently = 301 // RFC 7231, 6.4.2
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusMultipleChoices = 300 // RFC 7231, 6.4.1
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusMultiStatus = 207 // RFC 4918, 11.1
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusNoContent = 204 // RFC 7231, 6.3.5
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusNonAuthoritativeInfo = 203 // RFC 7231, 6.3.4
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusNotAcceptable = 406 // RFC 7231, 6.5.6
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusNotExtended = 510 // RFC 2774, 7
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusNotFound = 404 // RFC 7231, 6.5.4
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusNotImplemented = 501 // RFC 7231, 6.6.2
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusNotModified = 304 // RFC 7232, 4.1
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusOK = 200 // RFC 7231, 6.3.1
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusPartialContent = 206 // RFC 7233, 4.1
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusPaymentRequired = 402 // RFC 7231, 6.5.2
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusPermanentRedirect = 308 // RFC 7538, 3
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusPreconditionFailed = 412 // RFC 7232, 4.2
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusPreconditionRequired = 428 // RFC 6585, 3
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusProcessing = 102 // RFC 2518, 10.1
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusProxyAuthRequired = 407 // RFC 7235, 3.2
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusRequestedRangeNotSatisfiable = 416 // RFC 7233, 4.4
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusRequestEntityTooLarge = 413 // RFC 7231, 6.5.11
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusRequestHeaderFieldsTooLarge = 431 // RFC 6585, 5
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusRequestTimeout = 408 // RFC 7231, 6.5.7
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusRequestURITooLong = 414 // RFC 7231, 6.5.12
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusResetContent = 205 // RFC 7231, 6.3.6
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusSeeOther = 303 // RFC 7231, 6.4.4
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusServiceUnavailable = 503 // RFC 7231, 6.6.4
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusSwitchingProtocols = 101 // RFC 7231, 6.2.2
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusTeapot = 418 // RFC 7168, 2.3.3
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusTemporaryRedirect = 307 // RFC 7231, 6.4.7
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
func StatusText(code int) string
StatusText returns a text for the HTTP status code. It returns the empty
string if the code is unknown.
const StatusTooEarly = 425 // RFC 8470, 5.2.
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusTooManyRequests = 429 // RFC 6585, 4
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusUnauthorized = 401 // RFC 7235, 3.1
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusUnavailableForLegalReasons = 451 // RFC 7725, 3
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusUnprocessableEntity = 422 // RFC 4918, 11.2
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusUnsupportedMediaType = 415 // RFC 7231, 6.5.13
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusUpgradeRequired = 426 // RFC 7231, 6.5.15
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusUseProxy = 305 // RFC 7231, 6.4.5
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const StatusVariantAlsoNegotiates = 506 // RFC 2295, 8.1
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
func StripPrefix(prefix string, h Handler) Handler
StripPrefix returns a handler that serves HTTP requests
by removing the given prefix from the request URL's Path
and invoking the handler h. StripPrefix handles a
request for a path that doesn't begin with prefix by
replying with an HTTP 404 not found error.
const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"
TimeFormat is the time format to use when generating times in HTTP
headers. It is like time.RFC1123 but hard-codes GMT as the time
zone. The time being formatted must be in UTC for Format to
generate the correct format.
For parsing this time format, see ParseTime.
func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler
TimeoutHandler returns a Handler that runs h with the given time limit.
The new Handler calls h.ServeHTTP to handle each request, but if a
call runs for longer than its time limit, the handler responds with
a 503 Service Unavailable error and the given message in its body.
(If msg is empty, a suitable default message will be sent.)
After such a timeout, writes by h to its ResponseWriter will return
ErrHandlerTimeout.
TimeoutHandler supports the Pusher interface but does not support
the Hijacker or Flusher interfaces.
const TrailerPrefix = "Trailer:"
TrailerPrefix is a magic prefix for ResponseWriter.Header map keys
that, if present, signals that the map entry is actually for
the response trailers, and not the response headers. The prefix
is stripped after the ServeHTTP call finishes and the values are
sent in the trailers.
This mechanism is intended only for trailers that are not known
prior to the headers being written. If the set of trailers is fixed
or known before the header is written, the normal Go trailers mechanism
is preferred:
https://golang.org/pkg/net/http/#ResponseWriter
https://golang.org/pkg/net/http/#example_ResponseWriter_trailers
The pages are generated with Goldsv0.1.6. (GOOS=darwin GOARCH=amd64)
Golds is a Go 101 project and developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds.