version: 1.10

package http

import "net/http"

Overview

Package http provides HTTP client and server implementations.

Get, Head, Post, and PostForm make HTTP (or HTTPS) requests:

  1. resp, err := http.Get("http://example.com/")
  2. ...
  3. resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf)
  4. ...
  5. resp, err := http.PostForm("http://example.com/form",
  6. url.Values{"key": {"Value"}, "id": {"123"}})

The client must close the response body when finished with it:

  1. resp, err := http.Get("http://example.com/")
  2. if err != nil {
  3. // handle error
  4. }
  5. defer resp.Body.Close()
  6. body, err := ioutil.ReadAll(resp.Body)
  7. // ...

For control over HTTP client headers, redirect policy, and other settings,
create a Client:

  1. client := &http.Client{
  2. CheckRedirect: redirectPolicyFunc,
  3. }
  4. resp, err := client.Get("http://example.com")
  5. // ...
  6. req, err := http.NewRequest("GET", "http://example.com", nil)
  7. // ...
  8. req.Header.Add("If-None-Match", `W/"wyzzy"`)
  9. resp, err := client.Do(req)
  10. // ...

For control over proxies, TLS configuration, keep-alives, compression, and other
settings, create a Transport:

  1. tr := &http.Transport{
  2. MaxIdleConns: 10,
  3. IdleConnTimeout: 30 * time.Second,
  4. DisableCompression: true,
  5. }
  6. client := &http.Client{Transport: tr}
  7. resp, err := client.Get("https://example.com")

Clients and Transports are safe for concurrent use by multiple goroutines and
for efficiency should only be created once and re-used.

ListenAndServe starts an HTTP server with a given address and handler. The
handler is usually nil, which means to use DefaultServeMux. Handle and
HandleFunc add handlers to DefaultServeMux:

  1. http.Handle("/foo", fooHandler)
  2. http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
  3. fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
  4. })
  5. log.Fatal(http.ListenAndServe(":8080", nil))

More control over the server’s behavior is available by creating a custom
Server:

  1. s := &http.Server{
  2. Addr: ":8080",
  3. Handler: myHandler,
  4. ReadTimeout: 10 * time.Second,
  5. WriteTimeout: 10 * time.Second,
  6. MaxHeaderBytes: 1 << 20,
  7. }
  8. log.Fatal(s.ListenAndServe())

Starting with Go 1.6, the http package has transparent support for the HTTP/2
protocol when using HTTPS. Programs that must disable HTTP/2 can do so by
setting Transport.TLSNextProto (for clients) or Server.TLSNextProto (for
servers) to a non-nil, empty map. Alternatively, the following GODEBUG
environment variables are currently supported:

  1. GODEBUG=http2client=0 # disable HTTP/2 client support
  2. GODEBUG=http2server=0 # disable HTTP/2 server support
  3. GODEBUG=http2debug=1 # enable verbose HTTP/2 debug logs
  4. GODEBUG=http2debug=2 # ... even more verbose, with frame dumps

The GODEBUG variables are not covered by Go’s API compatibility promise. Please
report any issues before disabling HTTP/2 support: https://golang.org/s/http2bug

The http package’s Transport and Server both automatically enable HTTP/2 support
for simple configurations. To enable HTTP/2 for more complex configurations, to
use lower-level HTTP/2 features, or to use a newer version of Go’s http2
package, import “golang.org/x/net/http2” directly and use its ConfigureTransport
and/or ConfigureServer functions. Manually configuring HTTP/2 via the
golang.org/x/net/http2 package takes precedence over the net/http package’s
built-in HTTP/2 support.

Index

Examples

Package files

client.go cookie.go doc.go filetransport.go fs.go h2_bundle.go header.go http.go jar.go method.go request.go response.go server.go sniff.go status.go transfer.go transport.go

Constants

  1. const (
  2. MethodGet = "GET"
  3. MethodHead = "HEAD"
  4. MethodPost = "POST"
  5. MethodPut = "PUT"
  6. MethodPatch = "PATCH" // RFC 5789
  7. MethodDelete = "DELETE"
  8. MethodConnect = "CONNECT"
  9. MethodOptions = "OPTIONS"
  10. MethodTrace = "TRACE"
  11. )

Common HTTP methods.

Unless otherwise noted, these are defined in RFC 7231 section 4.3.

  1. const (
  2. StatusContinue = 100 // RFC 7231, 6.2.1
  3. StatusSwitchingProtocols = 101 // RFC 7231, 6.2.2
  4. StatusProcessing = 102 // RFC 2518, 10.1
  5.  
  6. StatusOK = 200 // RFC 7231, 6.3.1
  7. StatusCreated = 201 // RFC 7231, 6.3.2
  8. StatusAccepted = 202 // RFC 7231, 6.3.3
  9. StatusNonAuthoritativeInfo = 203 // RFC 7231, 6.3.4
  10. StatusNoContent = 204 // RFC 7231, 6.3.5
  11. StatusResetContent = 205 // RFC 7231, 6.3.6
  12. StatusPartialContent = 206 // RFC 7233, 4.1
  13. StatusMultiStatus = 207 // RFC 4918, 11.1
  14. StatusAlreadyReported = 208 // RFC 5842, 7.1
  15. StatusIMUsed = 226 // RFC 3229, 10.4.1
  16.  
  17. StatusMultipleChoices = 300 // RFC 7231, 6.4.1
  18. StatusMovedPermanently = 301 // RFC 7231, 6.4.2
  19. StatusFound = 302 // RFC 7231, 6.4.3
  20. StatusSeeOther = 303 // RFC 7231, 6.4.4
  21. StatusNotModified = 304 // RFC 7232, 4.1
  22. StatusUseProxy = 305 // RFC 7231, 6.4.5
  23.  
  24. StatusTemporaryRedirect = 307 // RFC 7231, 6.4.7
  25. StatusPermanentRedirect = 308 // RFC 7538, 3
  26.  
  27. StatusBadRequest = 400 // RFC 7231, 6.5.1
  28. StatusUnauthorized = 401 // RFC 7235, 3.1
  29. StatusPaymentRequired = 402 // RFC 7231, 6.5.2
  30. StatusForbidden = 403 // RFC 7231, 6.5.3
  31. StatusNotFound = 404 // RFC 7231, 6.5.4
  32. StatusMethodNotAllowed = 405 // RFC 7231, 6.5.5
  33. StatusNotAcceptable = 406 // RFC 7231, 6.5.6
  34. StatusProxyAuthRequired = 407 // RFC 7235, 3.2
  35. StatusRequestTimeout = 408 // RFC 7231, 6.5.7
  36. StatusConflict = 409 // RFC 7231, 6.5.8
  37. StatusGone = 410 // RFC 7231, 6.5.9
  38. StatusLengthRequired = 411 // RFC 7231, 6.5.10
  39. StatusPreconditionFailed = 412 // RFC 7232, 4.2
  40. StatusRequestEntityTooLarge = 413 // RFC 7231, 6.5.11
  41. StatusRequestURITooLong = 414 // RFC 7231, 6.5.12
  42. StatusUnsupportedMediaType = 415 // RFC 7231, 6.5.13
  43. StatusRequestedRangeNotSatisfiable = 416 // RFC 7233, 4.4
  44. StatusExpectationFailed = 417 // RFC 7231, 6.5.14
  45. StatusTeapot = 418 // RFC 7168, 2.3.3
  46. StatusUnprocessableEntity = 422 // RFC 4918, 11.2
  47. StatusLocked = 423 // RFC 4918, 11.3
  48. StatusFailedDependency = 424 // RFC 4918, 11.4
  49. StatusUpgradeRequired = 426 // RFC 7231, 6.5.15
  50. StatusPreconditionRequired = 428 // RFC 6585, 3
  51. StatusTooManyRequests = 429 // RFC 6585, 4
  52. StatusRequestHeaderFieldsTooLarge = 431 // RFC 6585, 5
  53. StatusUnavailableForLegalReasons = 451 // RFC 7725, 3
  54.  
  55. StatusInternalServerError = 500 // RFC 7231, 6.6.1
  56. StatusNotImplemented = 501 // RFC 7231, 6.6.2
  57. StatusBadGateway = 502 // RFC 7231, 6.6.3
  58. StatusServiceUnavailable = 503 // RFC 7231, 6.6.4
  59. StatusGatewayTimeout = 504 // RFC 7231, 6.6.5
  60. StatusHTTPVersionNotSupported = 505 // RFC 7231, 6.6.6
  61. StatusVariantAlsoNegotiates = 506 // RFC 2295, 8.1
  62. StatusInsufficientStorage = 507 // RFC 4918, 11.5
  63. StatusLoopDetected = 508 // RFC 5842, 7.2
  64. StatusNotExtended = 510 // RFC 2774, 7
  65. StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
  66. )

HTTP status codes as registered with IANA. See:
http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml

  1. const DefaultMaxHeaderBytes = 1 << 20 // 1 MB

DefaultMaxHeaderBytes is the maximum permitted size of the headers in an HTTP
request. This can be overridden by setting Server.MaxHeaderBytes.

  1. const DefaultMaxIdleConnsPerHost = 2

DefaultMaxIdleConnsPerHost is the default value of Transport’s
MaxIdleConnsPerHost.

  1. 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.

  1. 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:

  1. https://golang.org/pkg/net/http/#ResponseWriter
  2. https://golang.org/pkg/net/http/#example_ResponseWriter_trailers

Variables

  1. var (
  2. // ErrNotSupported is returned by the Push method of Pusher
  3. // implementations to indicate that HTTP/2 Push support is not
  4. // available.
  5. ErrNotSupported = &ProtocolError{"feature not supported"}
  6.  
  7. // ErrUnexpectedTrailer is returned by the Transport when a server
  8. // replies with a Trailer header, but without a chunked reply.
  9. ErrUnexpectedTrailer = &ProtocolError{"trailer header without chunked transfer encoding"}
  10.  
  11. // ErrMissingBoundary is returned by Request.MultipartReader when the
  12. // request's Content-Type does not include a "boundary" parameter.
  13. ErrMissingBoundary = &ProtocolError{"no multipart boundary param in Content-Type"}
  14.  
  15. // ErrNotMultipart is returned by Request.MultipartReader when the
  16. // request's Content-Type is not multipart/form-data.
  17. ErrNotMultipart = &ProtocolError{"request Content-Type isn't multipart/form-data"}
  18.  
  19. // Deprecated: ErrHeaderTooLong is not used.
  20. ErrHeaderTooLong = &ProtocolError{"header too long"}
  21. // Deprecated: ErrShortBody is not used.
  22. ErrShortBody = &ProtocolError{"entity body too short"}
  23. // Deprecated: ErrMissingContentLength is not used.
  24. ErrMissingContentLength = &ProtocolError{"missing ContentLength in HEAD response"}
  25. )
  1. var (
  2. // ErrBodyNotAllowed is returned by ResponseWriter.Write calls
  3. // when the HTTP method or response code does not permit a
  4. // body.
  5. ErrBodyNotAllowed = errors.New("http: request method or response status code does not allow body")
  6.  
  7. // ErrHijacked is returned by ResponseWriter.Write calls when
  8. // the underlying connection has been hijacked using the
  9. // Hijacker interface. A zero-byte write on a hijacked
  10. // connection will return ErrHijacked without any other side
  11. // effects.
  12. ErrHijacked = errors.New("http: connection has been hijacked")
  13.  
  14. // ErrContentLength is returned by ResponseWriter.Write calls
  15. // when a Handler set a Content-Length response header with a
  16. // declared size and then attempted to write more bytes than
  17. // declared.
  18. ErrContentLength = errors.New("http: wrote more than the declared Content-Length")
  19.  
  20. // Deprecated: ErrWriteAfterFlush is no longer used.
  21. ErrWriteAfterFlush = errors.New("unused")
  22. )

Errors used by the HTTP server.

  1. var (
  2. // ServerContextKey is a context key. It can be used in HTTP
  3. // handlers with context.WithValue to access the server that
  4. // started the handler. The associated value will be of
  5. // type *Server.
  6. ServerContextKey = &contextKey{"http-server"}
  7.  
  8. // LocalAddrContextKey is a context key. It can be used in
  9. // HTTP handlers with context.WithValue to access the address
  10. // the local address the connection arrived on.
  11. // The associated value will be of type net.Addr.
  12. LocalAddrContextKey = &contextKey{"local-addr"}
  13. )
  1. var DefaultClient = &Client{}

DefaultClient is the default Client and is used by Get, Head, and Post.

  1. var DefaultServeMux = &defaultServeMux

DefaultServeMux is the default ServeMux used by Serve.

  1. var ErrAbortHandler = errors.New("net/http: abort Handler")

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.

  1. var ErrBodyReadAfterClose = errors.New("http: invalid Read on closed Body")

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.

  1. var ErrHandlerTimeout = errors.New("http: Handler timeout")

ErrHandlerTimeout is returned on ResponseWriter Write calls in handlers which
have timed out.

  1. var ErrLineTooLong = internal.ErrLineTooLong

ErrLineTooLong is returned when reading request or response bodies with
malformed chunked encoding.

  1. var ErrMissingFile = errors.New("http: no such file")

ErrMissingFile is returned by FormFile when the provided file field name is
either not present in the request or not a file field.

  1. var ErrNoCookie = errors.New("http: named cookie not present")

ErrNoCookie is returned by Request’s Cookie method when a cookie is not found.

  1. var ErrNoLocation = errors.New("http: no Location header in response")

ErrNoLocation is returned by Response’s Location method when no Location header
is present.

  1. var ErrServerClosed = errors.New("http: Server closed")

ErrServerClosed is returned by the Server’s Serve, ServeTLS, ListenAndServe, and
ListenAndServeTLS methods after a call to Shutdown or Close.

  1. var ErrSkipAltProtocol = errors.New("net/http: skip alternate protocol")

ErrSkipAltProtocol is a sentinel error value defined by
Transport.RegisterProtocol.

  1. var ErrUseLastResponse = errors.New("net/http: use last response")

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.

  1. var NoBody = noBody{}

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 CanonicalHeaderKey

  1. 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.

func DetectContentType

  1. func DetectContentType(data []byte) string

DetectContentType implements the algorithm described at
http://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”.

func Error

  1. 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.

func Handle

  1. 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

  1. 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 ListenAndServe

  1. 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. Handler is typically nil, in which case
the DefaultServeMux is used.

A trivial example server is:

  1. package main
  2. import (
  3. "io"
  4. "net/http"
  5. "log"
  6. )
  7. // hello world, the web server
  8. func HelloServer(w http.ResponseWriter, req *http.Request) {
  9. io.WriteString(w, "hello, world!\n")
  10. }
  11. func main() {
  12. http.HandleFunc("/hello", HelloServer)
  13. log.Fatal(http.ListenAndServe(":12345", nil))
  14. }

ListenAndServe always returns a non-nil error.

func ListenAndServeTLS

  1. 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.

A trivial example server is:

  1. import (
  2. "log"
  3. "net/http"
  4. )
  5. func handler(w http.ResponseWriter, req *http.Request) {
  6. w.Header().Set("Content-Type", "text/plain")
  7. w.Write([]byte("This is an example server.\n"))
  8. }
  9. func main() {
  10. http.HandleFunc("/", handler)
  11. log.Printf("About to listen on 10443. Go to https://127.0.0.1:10443/")
  12. err := http.ListenAndServeTLS(":10443", "cert.pem", "key.pem", nil)
  13. log.Fatal(err)
  14. }

One can use generate_cert.go in crypto/tls to generate cert.pem and key.pem.

ListenAndServeTLS always returns a non-nil error.

func MaxBytesReader

  1. 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.

func NotFound

  1. func NotFound(w ResponseWriter, r *Request)

NotFound replies to the request with an HTTP 404 not found error.

func ParseHTTPVersion

  1. func ParseHTTPVersion(vers string) (major, minor int, ok bool)

ParseHTTPVersion parses a HTTP version string. “HTTP/1.0” returns (1, 0, true).

func ParseTime

  1. 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 ProxyFromEnvironment

  1. 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

  1. 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 Redirect

  1. 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.

func Serve

  1. 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. Handler is typically nil, in which case the
DefaultServeMux is used.

func ServeContent

  1. 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

  1. 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.

As a 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.

func ServeTLS

  1. 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.

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.

func SetCookie

  1. 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.

func StatusText

  1. func StatusText(code int) string

StatusText returns a text for the HTTP status code. It returns the empty string
if the code is unknown.

type Client

  1. type 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. // using the Request.Cancel mechanism. Requests passed
  44. // to Client.Do may still set Request.Cancel; both will
  45. // cancel the request.
  46. //
  47. // For compatibility, the Client will also use the deprecated
  48. // CancelRequest method on Transport if found. New
  49. // RoundTripper implementations should use Request.Cancel
  50. // instead of implementing CancelRequest.
  51. Timeout time.Duration
  52. }

A Client is an HTTP client. Its zero value (DefaultClient) is a usable client
that uses DefaultTransport.

The Client’s Transport typically has internal state (cached TCP connections), so
Clients should be reused instead of created as needed. Clients are safe for
concurrent use by multiple goroutines.

A Client is higher-level than a RoundTripper (such as Transport) and
additionally handles HTTP details such as cookies and redirects.

When following redirects, the Client will forward all headers set on the initial
Request except:

• when forwarding sensitive headers like “Authorization”, “WWW-Authenticate”,
and “Cookie” to untrusted targets. These headers will be ignored when following
a redirect to a domain that is not a subdomain match or exact match of the
initial domain. For example, a redirect from “foo.com” to either “foo.com” or
“sub.foo.com” will forward the sensitive headers, but a redirect to “bar.com”
will not.

• when forwarding the “Cookie” header with a non-nil cookie Jar. Since each
redirect may mutate the state of the cookie jar, a redirect may possibly alter a
cookie set in the initial request. When forwarding the “Cookie” header, any
mutated cookies will be omitted, with the expectation that the Jar will insert
those mutated cookies with the updated values (assuming the origin matches). If
Jar is nil, the initial cookies are forwarded without change.

func (*Client) Do

  1. func (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 closed, the Client’s underlying
RoundTripper (typically Transport) may not be able to re-use a persistent TCP
connection to the server for a subsequent “keep-alive” request.

The request Body, if non-nil, will be closed by the underlying Transport, even
on errors.

On error, any Response can be ignored. A non-nil Response with a non-nil error
only occurs when CheckRedirect fails, and even then the returned Response.Body
is already closed.

Generally Get, Post, or PostForm will be used instead of Do.

If the server replies with a redirect, the Client first uses the CheckRedirect
function to determine whether the redirect should be followed. If permitted, a
301, 302, or 303 redirect causes subsequent requests to use HTTP method GET (or
HEAD if the original request was HEAD), with no body. A 307 or 308 redirect
preserves the original HTTP method and body, provided that the Request.GetBody
function is defined. The NewRequest function automatically sets GetBody for
common standard library body types.

func (*Client) Get

  1. func (c *Client) Get(url string) (resp *Response, err error)

Get issues a GET to the specified URL. If the response is one of the following
redirect codes, Get follows the redirect after calling the Client’s
CheckRedirect function:

  1. 301 (Moved Permanently)
  2. 302 (Found)
  3. 303 (See Other)
  4. 307 (Temporary Redirect)
  5. 308 (Permanent Redirect)

An error is returned if the Client’s CheckRedirect function fails or if there
was an HTTP protocol error. A non-2xx response doesn’t cause an error.

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.

func (*Client) Head

  1. func (c *Client) Head(url string) (resp *Response, err error)

Head issues a HEAD to the specified URL. If the response is one of the following
redirect codes, Head follows the redirect after calling the Client’s
CheckRedirect function:

  1. 301 (Moved Permanently)
  2. 302 (Found)
  3. 303 (See Other)
  4. 307 (Temporary Redirect)
  5. 308 (Permanent Redirect)

func (*Client) Post

  1. func (c *Client) Post(url string, 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.

See the Client.Do method documentation for details on how redirects are handled.

func (*Client) PostForm

  1. func (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.

type CloseNotifier

  1. type CloseNotifier interface {
  2. // CloseNotify returns a channel that receives at most a
  3. // single value (true) when the client connection has gone
  4. // away.
  5. //
  6. // CloseNotify may wait to notify until Request.Body has been
  7. // fully read.
  8. //
  9. // After the Handler has returned, there is no guarantee
  10. // that the channel receives a value.
  11. //
  12. // If the protocol is HTTP/1.1 and CloseNotify is called while
  13. // processing an idempotent request (such a GET) while
  14. // HTTP/1.1 pipelining is in use, the arrival of a subsequent
  15. // pipelined request may cause a value to be sent on the
  16. // returned channel. In practice HTTP/1.1 pipelining is not
  17. // enabled in browsers and not seen often in the wild. If this
  18. // is a problem, use HTTP/2 or only use CloseNotify on methods
  19. // such as POST.
  20. CloseNotify() <-chan bool
  21. }

The CloseNotifier interface is implemented by ResponseWriters which allow
detecting when the underlying connection has gone away.

This mechanism can be used to cancel long operations on the server if the client
has disconnected before the response is ready.

type ConnState

  1. type ConnState int

A ConnState represents the state of a client connection to a server. It’s used
by the optional Server.ConnState hook.

  1. const (
  2. // StateNew represents a new connection that is expected to
  3. // send a request immediately. Connections begin at this
  4. // state and then transition to either StateActive or
  5. // StateClosed.
  6. StateNew ConnState = iota
  7.  
  8. // StateActive represents a connection that has read 1 or more
  9. // bytes of a request. The Server.ConnState hook for
  10. // StateActive fires before the request has entered a handler
  11. // and doesn't fire again until the request has been
  12. // handled. After the request is handled, the state
  13. // transitions to StateClosed, StateHijacked, or StateIdle.
  14. // For HTTP/2, StateActive fires on the transition from zero
  15. // to one active request, and only transitions away once all
  16. // active requests are complete. That means that ConnState
  17. // cannot be used to do per-request work; ConnState only notes
  18. // the overall state of the connection.
  19. StateActive
  20.  
  21. // StateIdle represents a connection that has finished
  22. // handling a request and is in the keep-alive state, waiting
  23. // for a new request. Connections transition from StateIdle
  24. // to either StateActive or StateClosed.
  25. StateIdle
  26.  
  27. // StateHijacked represents a hijacked connection.
  28. // This is a terminal state. It does not transition to StateClosed.
  29. StateHijacked
  30.  
  31. // StateClosed represents a closed connection.
  32. // This is a terminal state. Hijacked connections do not
  33. // transition to StateClosed.
  34. StateClosed
  35. )

func (ConnState) String

  1. func (c ConnState) String() string

  1. type Cookie struct {
  2. Name string
  3. Value string
  4.  
  5. Path string // optional
  6. Domain string // optional
  7. Expires time.Time // optional
  8. RawExpires string // for reading cookies only
  9.  
  10. // MaxAge=0 means no 'Max-Age' attribute specified.
  11. // MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'
  12. // MaxAge>0 means Max-Age attribute present and given in seconds
  13. MaxAge int
  14. Secure bool
  15. HttpOnly bool
  16. Raw string
  17. Unparsed []string // Raw text of unparsed attribute-value pairs
  18. }

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 http://tools.ietf.org/html/rfc6265 for details.

func (*Cookie) String

  1. func (c *Cookie) String() string

String returns the serialization of the cookie for use in a Cookie header (if
only Name and Value are set) or a Set-Cookie response header (if other fields
are set). If c is nil or c.Name is invalid, the empty string is returned.

type CookieJar

  1. type 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 Dir

  1. type Dir string

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 will allow access to files and directories starting with a period,
which could expose sensitive directories like a .git directory 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 “.”.

func (Dir) Open

  1. func (d Dir) Open(name string) (File, error)

type File

  1. type File interface {
  2. io.Closer
  3. io.Reader
  4. io.Seeker
  5. Readdir(count int) ([]os.FileInfo, error)
  6. Stat() (os.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

  1. type 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.

type Flusher

  1. type 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

  1. type Handler interface {
  2. ServeHTTP(ResponseWriter, *Request)
  3. }

A Handler responds to an HTTP request.

ServeHTTP should write reply headers and data to the ResponseWriter and then
return. Returning signals that the request is finished; it is not valid to use
the ResponseWriter or read from the Request.Body after or concurrently with the
completion of the ServeHTTP call.

Depending on the HTTP client software, HTTP protocol version, and any
intermediaries between the client and the Go server, it may not be possible to
read from the Request.Body after writing to the ResponseWriter. Cautious
handlers should read the Request.Body first, and then reply.

Except for reading the body, handlers should not modify the provided Request.

If ServeHTTP panics, the server (the caller of ServeHTTP) assumes that the
effect of the panic was isolated to the active request. It recovers the panic,
logs a stack trace to the server error log, and either closes the network
connection or sends an HTTP/2 RST_STREAM, depending on the HTTP protocol. To
abort a handler so the client sees an interrupted response but the server
doesn’t log an error, panic with the value ErrAbortHandler.

func FileServer

  1. 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:

  1. 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”.


Example:

  1. // Simple static webserver:
  2. log.Fatal(http.ListenAndServe(":8080", http.FileServer(http.Dir("/usr/share/doc"))))


Example:

  1. // To serve a directory on disk (/tmp) under an alternate URL
  2. // path (/tmpfiles/), use StripPrefix to modify the request
  3. // URL's path before the FileServer sees it:
  4. http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))

func NotFoundHandler

  1. func NotFoundHandler() Handler

NotFoundHandler returns a simple request handler that replies to each request
with a ``404 page not found’’ reply.

func RedirectHandler

  1. 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 StripPrefix

  1. 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.


Example:

  1. // To serve a directory on disk (/tmp) under an alternate URL
  2. // path (/tmpfiles/), use StripPrefix to modify the request
  3. // URL's path before the FileServer sees it:
  4. http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))

func TimeoutHandler

  1. 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 buffers all Handler writes to memory and does not support the
Hijacker or Flusher interfaces.

type HandlerFunc

  1. type HandlerFunc func(ResponseWriter, *Request)

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.

func (HandlerFunc) ServeHTTP

  1. func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request)

ServeHTTP calls f(w, r).

  1. type Header map[string][]string

A Header represents the key-value pairs in an HTTP header.

func (Header) Add

  1. func (h Header) Add(key, value string)

Add adds the key, value pair to the header. It appends to any existing values
associated with key.

func (Header) Del

  1. func (h Header) Del(key string)

Del deletes the values associated with key.

func (Header) Get

  1. func (h Header) Get(key string) string

Get gets the first value associated with the given key. It is case insensitive;
textproto.CanonicalMIMEHeaderKey is used to canonicalize the provided key. If
there are no values associated with the key, Get returns “”. To access multiple
values of a key, or to use non-canonical keys, access the map directly.

func (Header) Set

  1. func (h Header) Set(key, value string)

Set sets the header entries associated with key to the single element value. It
replaces any existing values associated with key.

func (Header) Write

  1. func (h Header) Write(w io.Writer) error

Write writes a header in wire format.

func (Header) WriteSubset

  1. func (h Header) WriteSubset(w io.Writer, exclude map[string]bool) error

WriteSubset writes a header in wire format. If exclude is not nil, keys where
exclude[key] == true are not written.

type Hijacker

  1. type 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
  18. // not be used.
  19. Hijack() (net.Conn, *bufio.ReadWriter, error)
  20. }

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.


Example:

  1. http.HandleFunc("/hijack", func(w http.ResponseWriter, r *http.Request) {
  2. hj, ok := w.(http.Hijacker)
  3. if !ok {
  4. http.Error(w, "webserver doesn't support hijacking", http.StatusInternalServerError)
  5. return
  6. }
  7. conn, bufrw, err := hj.Hijack()
  8. if err != nil {
  9. http.Error(w, err.Error(), http.StatusInternalServerError)
  10. return
  11. }
  12. // Don't forget to close the connection:
  13. defer conn.Close()
  14. bufrw.WriteString("Now we're speaking raw TCP. Say hi: ")
  15. bufrw.Flush()
  16. s, err := bufrw.ReadString('\n')
  17. if err != nil {
  18. log.Printf("error reading string: %v", err)
  19. return
  20. }
  21. fmt.Fprintf(bufrw, "You said: %q\nBye.\n", s)
  22. bufrw.Flush()
  23. })

type ProtocolError

  1. type ProtocolError struct {
  2. ErrorString string
  3. }

ProtocolError represents an HTTP protocol error.

Deprecated: Not all errors in the http package related to protocol errors are of
type ProtocolError.

func (*ProtocolError) Error

  1. func (pe *ProtocolError) Error() string

type PushOptions

  1. type PushOptions struct {
  2. // Method specifies the HTTP method for the promised request.
  3. // If set, it must be "GET" or "HEAD". Empty means "GET".
  4. Method string
  5.  
  6. // Header specifies additional promised request headers. This cannot
  7. // include HTTP/2 pseudo header fields like ":path" and ":scheme",
  8. // which will be added automatically.
  9. Header Header
  10. }

PushOptions describes options for Pusher.Push.

type Pusher

  1. type 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 returns ErrNotSupported if the client has disabled push or if push
  21. // is not supported on the underlying connection.
  22. Push(target string, opts *PushOptions) error
  23. }

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

  1. type Request struct {
  2. // Method specifies the HTTP method (GET, POST, PUT, etc.).
  3. // For client requests an empty string means GET.
  4. //
  5. // Go's HTTP client does not support sending a request with
  6. // the CONNECT method. See the documentation on Transport for
  7. // details.
  8. Method string
  9.  
  10. // URL specifies either the URI being requested (for server
  11. // requests) or the URL to access (for client requests).
  12. //
  13. // For server requests the URL is parsed from the URI
  14. // supplied on the Request-Line as stored in RequestURI. For
  15. // most requests, fields other than Path and RawQuery will be
  16. // empty. (See RFC 2616, Section 5.1.2)
  17. //
  18. // For client requests, the URL's Host specifies the server to
  19. // connect to, while the Request's Host field optionally
  20. // specifies the Host header value to send in the HTTP
  21. // request.
  22. URL *url.URL
  23.  
  24. // The protocol version for incoming server requests.
  25. //
  26. // For client requests these fields are ignored. The HTTP
  27. // client code always uses either HTTP/1.1 or HTTP/2.
  28. // See the docs on Transport for details.
  29. Proto string // "HTTP/1.0"
  30. ProtoMajor int // 1
  31. ProtoMinor int // 0
  32.  
  33. // Header contains the request header fields either received
  34. // by the server or to be sent by the client.
  35. //
  36. // If a server received a request with header lines,
  37. //
  38. // Host: example.com
  39. // accept-encoding: gzip, deflate
  40. // Accept-Language: en-us
  41. // fOO: Bar
  42. // foo: two
  43. //
  44. // then
  45. //
  46. // Header = map[string][]string{
  47. // "Accept-Encoding": {"gzip, deflate"},
  48. // "Accept-Language": {"en-us"},
  49. // "Foo": {"Bar", "two"},
  50. // }
  51. //
  52. // For incoming requests, the Host header is promoted to the
  53. // Request.Host field and removed from the Header map.
  54. //
  55. // HTTP defines that header names are case-insensitive. The
  56. // request parser implements this by using CanonicalHeaderKey,
  57. // making the first character and any characters following a
  58. // hyphen uppercase and the rest lowercase.
  59. //
  60. // For client requests, certain headers such as Content-Length
  61. // and Connection are automatically written when needed and
  62. // values in Header may be ignored. See the documentation
  63. // for the Request.Write method.
  64. Header Header
  65.  
  66. // Body is the request's body.
  67. //
  68. // For client requests a nil body means the request has no
  69. // body, such as a GET request. The HTTP Client's Transport
  70. // is responsible for calling the Close method.
  71. //
  72. // For server requests the Request Body is always non-nil
  73. // but will return EOF immediately when no body is present.
  74. // The Server will close the request body. The ServeHTTP
  75. // Handler does not need to.
  76. 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. // For client requests, a value of 0 with a non-nil Body is
  91. // also treated as unknown.
  92. ContentLength int64
  93.  
  94. // TransferEncoding lists the transfer encodings from outermost to
  95. // innermost. An empty list denotes the "identity" encoding.
  96. // TransferEncoding can usually be ignored; chunked encoding is
  97. // automatically added and removed as necessary when sending and
  98. // receiving requests.
  99. TransferEncoding []string
  100.  
  101. // Close indicates whether to close the connection after
  102. // replying to this request (for servers) or after sending this
  103. // request and reading its response (for clients).
  104. //
  105. // For server requests, the HTTP server handles this automatically
  106. // and this field is not needed by Handlers.
  107. //
  108. // For client requests, setting this field prevents re-use of
  109. // TCP connections between requests to the same hosts, as if
  110. // Transport.DisableKeepAlives were set.
  111. Close bool
  112.  
  113. // For server requests Host specifies the host on which the
  114. // URL is sought. Per RFC 2616, this is either the value of
  115. // the "Host" header or the host name given in the URL itself.
  116. // It may be of the form "host:port". For international domain
  117. // names, Host may be in Punycode or Unicode form. Use
  118. // golang.org/x/net/idna to convert it to either format if
  119. // needed.
  120. //
  121. // For client requests Host optionally overrides the Host
  122. // header to send. If empty, the Request.Write method uses
  123. // the value of URL.Host. Host may contain an international
  124. // domain name.
  125. Host string
  126.  
  127. // Form contains the parsed form data, including both the URL
  128. // field's query parameters and the POST or PUT form data.
  129. // This field is only available after ParseForm is called.
  130. // The HTTP client ignores Form and uses Body instead.
  131. Form url.Values
  132.  
  133. // PostForm contains the parsed form data from POST, PATCH,
  134. // or PUT body parameters.
  135. //
  136. // This field is only available after ParseForm is called.
  137. // The HTTP client ignores PostForm and uses Body instead.
  138. PostForm url.Values
  139.  
  140. // MultipartForm is the parsed multipart form, including file uploads.
  141. // This field is only available after ParseMultipartForm is called.
  142. // The HTTP client ignores MultipartForm and uses Body instead.
  143. MultipartForm *multipart.Form
  144.  
  145. // Trailer specifies additional headers that are sent after the request
  146. // body.
  147. //
  148. // For server requests the Trailer map initially contains only the
  149. // trailer keys, with nil values. (The client declares which trailers it
  150. // will later send.) While the handler is reading from Body, it must
  151. // not reference Trailer. After reading from Body returns EOF, Trailer
  152. // can be read again and will contain non-nil values, if they were sent
  153. // by the client.
  154. //
  155. // For client requests Trailer must be initialized to a map containing
  156. // the trailer keys to later send. The values may be nil or their final
  157. // values. The ContentLength must be 0 or -1, to send a chunked request.
  158. // After the HTTP request is sent the map values can be updated while
  159. // the request body is read. Once the body returns EOF, the caller must
  160. // not mutate Trailer.
  161. //
  162. // Few HTTP clients, servers, or proxies support HTTP trailers.
  163. Trailer Header
  164.  
  165. // RemoteAddr allows HTTP servers and other software to record
  166. // the network address that sent the request, usually for
  167. // logging. This field is not filled in by ReadRequest and
  168. // has no defined format. The HTTP server in this package
  169. // sets RemoteAddr to an "IP:port" address before invoking a
  170. // handler.
  171. // This field is ignored by the HTTP client.
  172. RemoteAddr string
  173.  
  174. // RequestURI is the unmodified Request-URI of the
  175. // Request-Line (RFC 2616, Section 5.1) as sent by the client
  176. // to a server. Usually the URL field should be used instead.
  177. // It is an error to set this field in an HTTP client request.
  178. RequestURI string
  179.  
  180. // TLS allows HTTP servers and other software to record
  181. // information about the TLS connection on which the request
  182. // was received. This field is not filled in by ReadRequest.
  183. // The HTTP server in this package sets the field for
  184. // TLS-enabled connections before invoking a handler;
  185. // otherwise it leaves the field nil.
  186. // This field is ignored by the HTTP client.
  187. TLS *tls.ConnectionState
  188.  
  189. // Cancel is an optional channel whose closure indicates that the client
  190. // request should be regarded as canceled. Not all implementations of
  191. // RoundTripper may support Cancel.
  192. //
  193. // For server requests, this field is not applicable.
  194. //
  195. // Deprecated: Use the Context and WithContext methods
  196. // instead. If a Request's Cancel field and context are both
  197. // set, it is undefined whether Cancel is respected.
  198. Cancel <-chan struct{}
  199.  
  200. // Response is the redirect response which caused this request
  201. // to be created. This field is only populated during client
  202. // redirects.
  203. Response *Response
  204. // contains filtered or unexported fields
  205. }

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 NewRequest

  1. func NewRequest(method, url string, body io.Reader) (*Request, error)

NewRequest 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.

NewRequest 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. 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 ReadRequest

  1. func ReadRequest(b *bufio.Reader) (*Request, error)

ReadRequest reads and parses an incoming request from b.

func (*Request) AddCookie

  1. func (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.

func (*Request) BasicAuth

  1. func (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 (*Request) Context

  1. func (r *Request) Context() context.Context

Context returns the request’s context. To change the context, use WithContext.

The returned context is always non-nil; it defaults to the background context.

For outgoing client requests, the context controls cancelation.

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 (*Request) Cookie

  1. func (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 (*Request) Cookies

  1. func (r *Request) Cookies() []*Cookie

Cookies parses and returns the HTTP cookies sent with the request.

func (*Request) FormFile

  1. func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error)

FormFile returns the first file for the provided form key. FormFile calls
ParseMultipartForm and ParseForm if necessary.

func (*Request) FormValue

  1. func (r *Request) FormValue(key string) string

FormValue returns the first value for the named component of the query. POST and
PUT body parameters take precedence over URL query string values. FormValue
calls ParseMultipartForm and ParseForm if necessary and ignores any errors
returned by these functions. If key is not present, FormValue returns the empty
string. To access multiple values of the same key, call ParseForm and then
inspect Request.Form directly.

func (*Request) MultipartReader

  1. func (r *Request) MultipartReader() (*multipart.Reader, error)

MultipartReader returns a MIME multipart reader if this is a multipart/form-data
POST request, else returns nil and an error. Use this function instead of
ParseMultipartForm to process the request body as a stream.

func (*Request) ParseForm

  1. func (r *Request) ParseForm() error

ParseForm populates r.Form and r.PostForm.

For all requests, ParseForm parses the raw query from the URL and updates
r.Form.

For POST, PUT, and PATCH requests, it also parses the request body 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.

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.

If the request Body’s size has not already been limited by MaxBytesReader, the
size is capped at 10MB.

ParseMultipartForm calls ParseForm automatically. ParseForm is idempotent.

func (*Request) ParseMultipartForm

  1. func (r *Request) ParseMultipartForm(maxMemory int64) error

ParseMultipartForm parses a request body as multipart/form-data. The whole
request body is parsed and up to a total of maxMemory bytes of its file parts
are stored in memory, with the remainder stored on disk in temporary files.
ParseMultipartForm calls ParseForm if necessary. After one call to
ParseMultipartForm, subsequent calls have no effect.

func (*Request) PostFormValue

  1. func (r *Request) PostFormValue(key string) string

PostFormValue returns the first value for the named component of the POST or PUT
request body. URL query parameters are ignored. PostFormValue calls
ParseMultipartForm and ParseForm if necessary and ignores any errors returned by
these functions. If key is not present, PostFormValue returns the empty string.

func (*Request) ProtoAtLeast

  1. func (r *Request) ProtoAtLeast(major, minor int) bool

ProtoAtLeast reports whether the HTTP protocol used in the request is at least
major.minor.

func (*Request) Referer

  1. func (r *Request) Referer() string

Referer returns the referring URL, if sent in the request.

Referer is misspelled as in the request itself, a mistake from the earliest days
of HTTP. This value can also be fetched from the Header map as
Header[“Referer”]; the benefit of making it available as a method is that the
compiler can diagnose programs that use the alternate (correct English) spelling
req.Referrer() but cannot diagnose programs that use Header[“Referrer”].

func (*Request) SetBasicAuth

  1. func (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.

func (*Request) UserAgent

  1. func (r *Request) UserAgent() string

UserAgent returns the client’s User-Agent, if sent in the request.

func (*Request) WithContext

  1. func (r *Request) WithContext(ctx context.Context) *Request

WithContext returns a shallow copy of r with its context changed to ctx. The
provided ctx must be non-nil.

func (*Request) Write

  1. func (r *Request) Write(w io.Writer) error

Write writes an HTTP/1.1 request, which is the header and body, in wire format.
This method consults the following fields of the request:

  1. Host
  2. URL
  3. Method (defaults to "GET")
  4. Header
  5. ContentLength
  6. TransferEncoding
  7. Body

If Body is present, Content-Length is <= 0 and TransferEncoding hasn’t been set
to “identity”, Write adds “Transfer-Encoding: chunked” to the header. Body is
closed after it is sent.

func (*Request) WriteProxy

  1. func (r *Request) WriteProxy(w io.Writer) error

WriteProxy is like Write but writes the request in the form expected by an HTTP
proxy. In particular, WriteProxy writes the initial Request-URI line of the
request with an absolute URI, per section 5.1.2 of RFC 2616, including the
scheme and host. In either case, WriteProxy also writes a Host header, using
either r.Host or r.URL.Host.

type Response

  1. type 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. (Section 4.2 of RFC 2616 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. Body io.ReadCloser
  35.  
  36. // ContentLength records the length of the associated content. The
  37. // value -1 indicates that the length is unknown. Unless Request.Method
  38. // is "HEAD", values >= 0 indicate that the given number of bytes may
  39. // be read from Body.
  40. ContentLength int64
  41.  
  42. // Contains transfer encodings from outer-most to inner-most. Value is
  43. // nil, means that "identity" encoding is used.
  44. TransferEncoding []string
  45.  
  46. // Close records whether the header directed that the connection be
  47. // closed after reading Body. The value is advice for clients: neither
  48. // ReadResponse nor Response.Write ever closes a connection.
  49. Close bool
  50.  
  51. // Uncompressed reports whether the response was sent compressed but
  52. // was decompressed by the http package. When true, reading from
  53. // Body yields the uncompressed content instead of the compressed
  54. // content actually set from the server, ContentLength is set to -1,
  55. // and the "Content-Length" and "Content-Encoding" fields are deleted
  56. // from the responseHeader. To get the original response from
  57. // the server, set Transport.DisableCompression to true.
  58. Uncompressed bool
  59.  
  60. // Trailer maps trailer keys to values in the same
  61. // format as Header.
  62. //
  63. // The Trailer initially contains only nil values, one for
  64. // each key specified in the server's "Trailer" header
  65. // value. Those values are not added to Header.
  66. //
  67. // Trailer must not be accessed concurrently with Read calls
  68. // on the Body.
  69. //
  70. // After Body.Read has returned io.EOF, Trailer will contain
  71. // any trailer values sent by the server.
  72. Trailer Header
  73.  
  74. // Request is the request that was sent to obtain this Response.
  75. // Request's Body is nil (having already been consumed).
  76. // This is only populated for Client requests.
  77. Request *Request
  78.  
  79. // TLS contains information about the TLS connection on which the
  80. // response was received. It is nil for unencrypted responses.
  81. // The pointer is shared between responses and should not be
  82. // modified.
  83. TLS *tls.ConnectionState
  84. }

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 Get

  1. 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:

  1. 301 (Moved Permanently)
  2. 302 (Found)
  3. 303 (See Other)
  4. 307 (Temporary Redirect)
  5. 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.

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.


Example:

  1. res, err := http.Get("http://www.google.com/robots.txt")
  2. if err != nil {
  3. log.Fatal(err)
  4. }
  5. robots, err := ioutil.ReadAll(res.Body)
  6. res.Body.Close()
  7. if err != nil {
  8. log.Fatal(err)
  9. }
  10. fmt.Printf("%s", robots)

  1. 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:

  1. 301 (Moved Permanently)
  2. 302 (Found)
  3. 303 (See Other)
  4. 307 (Temporary Redirect)
  5. 308 (Permanent Redirect)

Head is a wrapper around DefaultClient.Head

func Post

  1. func Post(url string, 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

  1. 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 ReadResponse

  1. 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 (*Response) Cookies

  1. func (r *Response) Cookies() []*Cookie

Cookies parses and returns the cookies set in the Set-Cookie headers.

func (*Response) Location

  1. func (r *Response) Location() (*url.URL, error)

Location returns the URL of the response’s “Location” header, if present.
Relative redirects are resolved relative to the Response’s Request.
ErrNoLocation is returned if no Location header is present.

func (*Response) ProtoAtLeast

  1. func (r *Response) ProtoAtLeast(major, minor int) bool

ProtoAtLeast reports whether the HTTP protocol used in the response is at least
major.minor.

func (*Response) Write

  1. func (r *Response) Write(w io.Writer) error

Write writes r to w in the HTTP/1.x server response format, including the status
line, headers, body, and optional trailer.

This method consults the following fields of the response r:

  1. StatusCode
  2. ProtoMajor
  3. ProtoMinor
  4. Request.Method
  5. TransferEncoding
  6. Trailer
  7. Body
  8. ContentLength
  9. Header, values for non-canonical keys will have unpredictable behavior

The Response Body is closed after it is sent.

type ResponseWriter

  1. type ResponseWriter interface {
  2. // Header returns the header map that will be sent by
  3. // WriteHeader. The Header map also is the mechanism with which
  4. // Handlers can set HTTP trailers.
  5. //
  6. // Changing the header map after a call to WriteHeader (or
  7. // Write) has no effect unless the modified headers are
  8. // trailers.
  9. //
  10. // There are two ways to set Trailers. The preferred way is to
  11. // predeclare in the headers which trailers you will later
  12. // send by setting the "Trailer" header to the names of the
  13. // trailer keys which will come later. In this case, those
  14. // keys of the Header map are treated as if they were
  15. // trailers. See the example. The second way, for trailer
  16. // keys not known to the Handler until after the first Write,
  17. // is to prefix the Header map keys with the TrailerPrefix
  18. // constant value. See TrailerPrefix.
  19. //
  20. // To suppress implicit response headers (such as "Date"), set
  21. // their value to nil.
  22. Header() Header
  23.  
  24. // Write writes the data to the connection as part of an HTTP reply.
  25. //
  26. // If WriteHeader has not yet been called, Write calls
  27. // WriteHeader(http.StatusOK) before writing the data. If the Header
  28. // does not contain a Content-Type line, Write adds a Content-Type set
  29. // to the result of passing the initial 512 bytes of written data to
  30. // DetectContentType.
  31. //
  32. // Depending on the HTTP protocol version and the client, calling
  33. // Write or WriteHeader may prevent future reads on the
  34. // Request.Body. For HTTP/1.x requests, handlers should read any
  35. // needed request body data before writing the response. Once the
  36. // headers have been flushed (due to either an explicit Flusher.Flush
  37. // call or writing enough data to trigger a flush), the request body
  38. // may be unavailable. For HTTP/2 requests, the Go HTTP server permits
  39. // handlers to continue to read the request body while concurrently
  40. // writing the response. However, such behavior may not be supported
  41. // by all HTTP/2 clients. Handlers should read before writing if
  42. // possible to maximize compatibility.
  43. Write([]byte) (int, error)
  44.  
  45. // WriteHeader sends an HTTP response header with the provided
  46. // status code.
  47. //
  48. // If WriteHeader is not called explicitly, the first call to Write
  49. // will trigger an implicit WriteHeader(http.StatusOK).
  50. // Thus explicit calls to WriteHeader are mainly used to
  51. // send error codes.
  52. //
  53. // The provided code must be a valid HTTP 1xx-5xx status code.
  54. // Only one header may be written. Go does not currently
  55. // support sending user-defined 1xx informational headers,
  56. // with the exception of 100-continue response header that the
  57. // Server sends automatically when the Request.Body is read.
  58. WriteHeader(statusCode int)
  59. }

A ResponseWriter interface is used by an HTTP handler to construct an HTTP
response.

A ResponseWriter may not be used after the Handler.ServeHTTP method has
returned.


Example:

  1. mux := http.NewServeMux()
  2. mux.HandleFunc("/sendstrailers", func(w http.ResponseWriter, req *http.Request) {
  3. // Before any call to WriteHeader or Write, declare
  4. // the trailers you will set during the HTTP
  5. // response. These three headers are actually sent in
  6. // the trailer.
  7. w.Header().Set("Trailer", "AtEnd1, AtEnd2")
  8. w.Header().Add("Trailer", "AtEnd3")
  9. w.Header().Set("Content-Type", "text/plain; charset=utf-8") // normal header
  10. w.WriteHeader(http.StatusOK)
  11. w.Header().Set("AtEnd1", "value 1")
  12. io.WriteString(w, "This HTTP response has both headers before this text and trailers at the end.\n")
  13. w.Header().Set("AtEnd2", "value 2")
  14. w.Header().Set("AtEnd3", "value 3") // These will appear as trailers.
  15. })

type RoundTripper

  1. type 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 the request until the Response's Body has
  17. // 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.

  1. var DefaultTransport RoundTripper = &Transport{
  2. Proxy: ProxyFromEnvironment,
  3. DialContext: (&net.Dialer{
  4. Timeout: 30 * time.Second,
  5. KeepAlive: 30 * time.Second,
  6. DualStack: true,
  7. }).DialContext,
  8. MaxIdleConns: 100,
  9. IdleConnTimeout: 90 * time.Second,
  10. TLSHandshakeTimeout: 10 * time.Second,
  11. ExpectContinueTimeout: 1 * time.Second,
  12. }

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 NewFileTransport

  1. 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:

  1. t := &http.Transport{}
  2. t.RegisterProtocol("file", http.NewFileTransport(http.Dir("/")))
  3. c := &http.Client{Transport: t}
  4. res, err := c.Get("file:///etc/passwd")
  5. ...

type ServeMux

  1. type ServeMux struct {
  2. // contains filtered or unexported fields
  3. }

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, redirecting any
request containing . or .. elements or repeated slashes to an equivalent,
cleaner URL.

func NewServeMux

  1. func NewServeMux() *ServeMux

NewServeMux allocates and returns a new ServeMux.

func (*ServeMux) Handle

  1. func (mux *ServeMux) Handle(pattern string, handler Handler)

Handle registers the handler for the given pattern. If a handler already exists
for pattern, Handle panics.


Example:

  1. mux := http.NewServeMux()
  2. mux.Handle("/api/", apiHandler{})
  3. mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
  4. // The "/" pattern matches everything, so we need to check
  5. // that we're at the root here.
  6. if req.URL.Path != "/" {
  7. http.NotFound(w, req)
  8. return
  9. }
  10. fmt.Fprintf(w, "Welcome to the home page!")
  11. })

func (*ServeMux) HandleFunc

  1. func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))

HandleFunc registers the handler function for the given pattern.

func (*ServeMux) Handler

  1. func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string)

Handler returns the handler to use for the given request, consulting r.Method,
r.Host, and r.URL.Path. It always returns a non-nil handler. If the path is not
in its canonical form, the handler will be an internally-generated handler that
redirects to the canonical path. If the host contains a port, it is ignored when
matching handlers.

The path and host are used unchanged for CONNECT requests.

Handler also returns the registered pattern that matches the request or, in the
case of internally-generated redirects, the pattern that will match after
following the redirect.

If there is no registered handler that applies to the request, Handler returns a
``page not found’’ handler and an empty pattern.

func (*ServeMux) ServeHTTP

  1. func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request)

ServeHTTP dispatches the request to the handler whose pattern most closely
matches the request URL.

type Server

  1. type Server struct {
  2. Addr string // TCP address to listen on, ":http" if empty
  3. Handler Handler // handler to invoke, http.DefaultServeMux if nil
  4.  
  5. // TLSConfig optionally provides a TLS configuration for use
  6. // by ServeTLS and ListenAndServeTLS. Note that this value is
  7. // cloned by ServeTLS and ListenAndServeTLS, so it's not
  8. // possible to modify the configuration with methods like
  9. // tls.Config.SetSessionTicketKeys. To use
  10. // SetSessionTicketKeys, use Server.Serve with a TLS Listener
  11. // instead.
  12. TLSConfig *tls.Config
  13.  
  14. // ReadTimeout is the maximum duration for reading the entire
  15. // request, including the body.
  16. //
  17. // Because ReadTimeout does not let Handlers make per-request
  18. // decisions on each request body's acceptable deadline or
  19. // upload rate, most users will prefer to use
  20. // ReadHeaderTimeout. It is valid to use them both.
  21. ReadTimeout time.Duration
  22.  
  23. // ReadHeaderTimeout is the amount of time allowed to read
  24. // request headers. The connection's read deadline is reset
  25. // after reading the headers and the Handler can decide what
  26. // is considered too slow for the body.
  27. ReadHeaderTimeout time.Duration
  28.  
  29. // WriteTimeout is the maximum duration before timing out
  30. // writes of the response. It is reset whenever a new
  31. // request's header is read. Like ReadTimeout, it does not
  32. // let Handlers make decisions on a per-request basis.
  33. WriteTimeout time.Duration
  34.  
  35. // IdleTimeout is the maximum amount of time to wait for the
  36. // next request when keep-alives are enabled. If IdleTimeout
  37. // is zero, the value of ReadTimeout is used. If both are
  38. // zero, ReadHeaderTimeout is used.
  39. IdleTimeout time.Duration
  40.  
  41. // MaxHeaderBytes controls the maximum number of bytes the
  42. // server will read parsing the request header's keys and
  43. // values, including the request line. It does not limit the
  44. // size of the request body.
  45. // If zero, DefaultMaxHeaderBytes is used.
  46. MaxHeaderBytes int
  47.  
  48. // TLSNextProto optionally specifies a function to take over
  49. // ownership of the provided TLS connection when an NPN/ALPN
  50. // protocol upgrade has occurred. The map key is the protocol
  51. // name negotiated. The Handler argument should be used to
  52. // handle HTTP requests and will initialize the Request's TLS
  53. // and RemoteAddr if not already set. The connection is
  54. // automatically closed when the function returns.
  55. // If TLSNextProto is not nil, HTTP/2 support is not enabled
  56. // automatically.
  57. TLSNextProto map[string]func(*Server, *tls.Conn, Handler)
  58.  
  59. // ConnState specifies an optional callback function that is
  60. // called when a client connection changes state. See the
  61. // ConnState type and associated constants for details.
  62. ConnState func(net.Conn, ConnState)
  63.  
  64. // ErrorLog specifies an optional logger for errors accepting
  65. // connections, unexpected behavior from handlers, and
  66. // underlying FileSystem errors.
  67. // If nil, logging is done via the log package's standard logger.
  68. ErrorLog *log.Logger
  69. // contains filtered or unexported fields
  70. }

A Server defines parameters for running an HTTP server. The zero value for
Server is a valid configuration.

func (*Server) Close

  1. func (srv *Server) Close() error

Close immediately closes all active net.Listeners and any connections in state
StateNew, StateActive, or StateIdle. For a graceful shutdown, use Shutdown.

Close does not attempt to close (and does not even know about) any hijacked
connections, such as WebSockets.

Close returns any error returned from closing the Server’s underlying
Listener(s).

func (*Server) ListenAndServe

  1. func (srv *Server) ListenAndServe() error

ListenAndServe listens on the TCP network address srv.Addr and then calls Serve
to handle requests on incoming connections. Accepted connections are configured
to enable TCP keep-alives. If srv.Addr is blank, “:http” is used. ListenAndServe
always returns a non-nil error.

func (*Server) ListenAndServeTLS

  1. func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error

ListenAndServeTLS listens on the TCP network address srv.Addr and then calls
Serve to handle requests on incoming TLS connections. Accepted connections are
configured to enable TCP keep-alives.

Filenames containing a certificate and matching private key for the server must
be provided if neither the Server’s TLSConfig.Certificates nor
TLSConfig.GetCertificate are populated. 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.

If srv.Addr is blank, “:https” is used.

ListenAndServeTLS always returns a non-nil error.

func (*Server) RegisterOnShutdown

  1. func (srv *Server) RegisterOnShutdown(f func())

RegisterOnShutdown registers a function to call on Shutdown. This can be used to
gracefully shutdown connections that have undergone NPN/ALPN protocol upgrade or
that have been hijacked. This function should start protocol-specific graceful
shutdown, but should not wait for shutdown to complete.

func (*Server) Serve

  1. func (srv *Server) Serve(l net.Listener) error

Serve accepts incoming connections on the Listener l, creating a new service
goroutine for each. The service goroutines read requests and then call
srv.Handler to reply to them.

For HTTP/2 support, srv.TLSConfig should be initialized to the provided
listener’s TLS Config before calling Serve. If srv.TLSConfig is non-nil and
doesn’t include the string “h2” in Config.NextProtos, HTTP/2 support is not
enabled.

Serve always returns a non-nil error. After Shutdown or Close, the returned
error is ErrServerClosed.

func (*Server) ServeTLS

  1. func (srv *Server) ServeTLS(l net.Listener, certFile, keyFile string) error

ServeTLS accepts incoming connections on the Listener l, creating a new service
goroutine for each. The service goroutines read requests and then call
srv.Handler to reply to them.

Additionally, files containing a certificate and matching private key for the
server must be provided if neither the Server’s TLSConfig.Certificates nor
TLSConfig.GetCertificate are populated.. 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.

For HTTP/2 support, srv.TLSConfig should be initialized to the provided
listener’s TLS Config before calling ServeTLS. If srv.TLSConfig is non-nil and
doesn’t include the string “h2” in Config.NextProtos, HTTP/2 support is not
enabled.

ServeTLS always returns a non-nil error. After Shutdown or Close, the returned
error is ErrServerClosed.

func (*Server) SetKeepAlivesEnabled

  1. func (srv *Server) SetKeepAlivesEnabled(v bool)

SetKeepAlivesEnabled controls whether HTTP keep-alives are enabled. By default,
keep-alives are always enabled. Only very resource-constrained environments or
servers in the process of shutting down should disable them.

func (*Server) Shutdown

  1. func (srv *Server) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server without interrupting any active
connections. Shutdown works by first closing all open listeners, then closing
all idle connections, and then waiting indefinitely for connections to return to
idle and then shut down. If the provided context expires before the shutdown is
complete, Shutdown returns the context’s error, otherwise it returns any error
returned from closing the Server’s underlying Listener(s).

When Shutdown is called, Serve, ListenAndServe, and ListenAndServeTLS
immediately return ErrServerClosed. Make sure the program doesn’t exit and waits
instead for Shutdown to return.

Shutdown does not attempt to close nor wait for hijacked connections such as
WebSockets. The caller of Shutdown should separately notify such long-lived
connections of shutdown and wait for them to close, if desired. See
RegisterOnShutdown for a way to register shutdown notification functions.


Example:

  1. var srv http.Server
  2. idleConnsClosed := make(chan struct{})
  3. go func() {
  4. sigint := make(chan os.Signal, 1)
  5. signal.Notify(sigint, os.Interrupt)
  6. <-sigint
  7. // We received an interrupt signal, shut down.
  8. if err := srv.Shutdown(context.Background()); err != nil {
  9. // Error from closing listeners, or context timeout:
  10. log.Printf("HTTP server Shutdown: %v", err)
  11. }
  12. close(idleConnsClosed)
  13. }()
  14. if err := srv.ListenAndServe(); err != http.ErrServerClosed {
  15. // Error starting or closing listener:
  16. log.Printf("HTTP server ListenAndServe: %v", err)
  17. }
  18. <-idleConnsClosed

type Transport

  1. type 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. // and "socks5" are supported. If the scheme is empty,
  9. // "http" is assumed.
  10. //
  11. // If Proxy is nil or returns a nil *URL, no proxy is used.
  12. Proxy func(*Request) (*url.URL, error)
  13.  
  14. // DialContext specifies the dial function for creating unencrypted TCP connections.
  15. // If DialContext is nil (and the deprecated Dial below is also nil),
  16. // then the transport dials using package net.
  17. DialContext func(ctx context.Context, network, addr string) (net.Conn, error)
  18.  
  19. // Dial specifies the dial function for creating unencrypted TCP connections.
  20. //
  21. // Deprecated: Use DialContext instead, which allows the transport
  22. // to cancel dials as soon as they are no longer needed.
  23. // If both are set, DialContext takes priority.
  24. Dial func(network, addr string) (net.Conn, error)
  25.  
  26. // DialTLS specifies an optional dial function for creating
  27. // TLS connections for non-proxied HTTPS requests.
  28. //
  29. // If DialTLS is nil, Dial and TLSClientConfig are used.
  30. //
  31. // If DialTLS is set, the Dial hook is not used for HTTPS
  32. // requests and the TLSClientConfig and TLSHandshakeTimeout
  33. // are ignored. The returned net.Conn is assumed to already be
  34. // past the TLS handshake.
  35. DialTLS func(network, addr string) (net.Conn, error)
  36.  
  37. // TLSClientConfig specifies the TLS configuration to use with
  38. // tls.Client.
  39. // If nil, the default configuration is used.
  40. // If non-nil, HTTP/2 support may not be enabled by default.
  41. TLSClientConfig *tls.Config
  42.  
  43. // TLSHandshakeTimeout specifies the maximum amount of time waiting to
  44. // wait for a TLS handshake. Zero means no timeout.
  45. TLSHandshakeTimeout time.Duration
  46.  
  47. // DisableKeepAlives, if true, prevents re-use of TCP connections
  48. // between different HTTP requests.
  49. DisableKeepAlives bool
  50.  
  51. // DisableCompression, if true, prevents the Transport from
  52. // requesting compression with an "Accept-Encoding: gzip"
  53. // request header when the Request contains no existing
  54. // Accept-Encoding value. If the Transport requests gzip on
  55. // its own and gets a gzipped response, it's transparently
  56. // decoded in the Response.Body. However, if the user
  57. // explicitly requested gzip it is not automatically
  58. // uncompressed.
  59. DisableCompression bool
  60.  
  61. // MaxIdleConns controls the maximum number of idle (keep-alive)
  62. // connections across all hosts. Zero means no limit.
  63. MaxIdleConns int
  64.  
  65. // MaxIdleConnsPerHost, if non-zero, controls the maximum idle
  66. // (keep-alive) connections to keep per-host. If zero,
  67. // DefaultMaxIdleConnsPerHost is used.
  68. MaxIdleConnsPerHost int
  69.  
  70. // IdleConnTimeout is the maximum amount of time an idle
  71. // (keep-alive) connection will remain idle before closing
  72. // itself.
  73. // Zero means no limit.
  74. IdleConnTimeout time.Duration
  75.  
  76. // ResponseHeaderTimeout, if non-zero, specifies the amount of
  77. // time to wait for a server's response headers after fully
  78. // writing the request (including its body, if any). This
  79. // time does not include the time to read the response body.
  80. ResponseHeaderTimeout time.Duration
  81.  
  82. // ExpectContinueTimeout, if non-zero, specifies the amount of
  83. // time to wait for a server's first response headers after fully
  84. // writing the request headers if the request has an
  85. // "Expect: 100-continue" header. Zero means no timeout and
  86. // causes the body to be sent immediately, without
  87. // waiting for the server to approve.
  88. // This time does not include the time to send the request header.
  89. ExpectContinueTimeout time.Duration
  90.  
  91. // TLSNextProto specifies how the Transport switches to an
  92. // alternate protocol (such as HTTP/2) after a TLS NPN/ALPN
  93. // protocol negotiation. If Transport dials an TLS connection
  94. // with a non-empty protocol name and TLSNextProto contains a
  95. // map entry for that key (such as "h2"), then the func is
  96. // called with the request's authority (such as "example.com"
  97. // or "example.com:1234") and the TLS connection. The function
  98. // must return a RoundTripper that then handles the request.
  99. // If TLSNextProto is not nil, HTTP/2 support is not enabled
  100. // automatically.
  101. TLSNextProto map[string]func(authority string, c *tls.Conn) RoundTripper
  102.  
  103. // ProxyConnectHeader optionally specifies headers to send to
  104. // proxies during CONNECT requests.
  105. ProxyConnectHeader Header
  106.  
  107. // MaxResponseHeaderBytes specifies a limit on how many
  108. // response bytes are allowed in the server's response
  109. // header.
  110. //
  111. // Zero means to use a default limit.
  112. MaxResponseHeaderBytes int64
  113. // contains filtered or unexported fields
  114. }

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.

The Transport will send CONNECT requests to a proxy for its own use when
processing HTTPS requests, but Transport should generally not be used to send a
CONNECT request. That is, the Request passed to the RoundTrip method should not
have a Method of “CONNECT”, as Go’s HTTP/1.x implementation does not support
full-duplex request bodies being written while the response body is streamed.
Go’s HTTP/2 implementation does support full duplex, but many CONNECT proxies
speak HTTP/1.x.

func (*Transport) CancelRequest

  1. func (t *Transport) CancelRequest(req *Request)

CancelRequest cancels an in-flight request by closing its connection.
CancelRequest should only be called after RoundTrip has returned.

Deprecated: Use Request.WithContext to create a request with a cancelable
context instead. CancelRequest cannot cancel HTTP/2 requests.

func (*Transport) CloseIdleConnections

  1. func (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 (*Transport) RegisterProtocol

  1. func (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
RoundTrip itself for that one request, as if the protocol were not registered.

func (*Transport) RoundTrip

  1. func (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.

Subdirectories