Documentation
¶
Overview ¶
Package http provides HTTP client and server implementations.
Get, Head, Post, and PostForm make HTTP (or HTTPS) requests:
resp, err := http.Get("http://example.com/")
...
resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf)
...
resp, err := http.PostForm("http://example.com/form",
url.Values{"key": {"Value"}, "id": {"123"}})
The client must close the response body when finished with it:
resp, err := http.Get("http://example.com/")
if err != nil {
// handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
// ...
For control over HTTP client headers, redirect policy, and other settings, create a Client:
client := &http.Client{
CheckRedirect: redirectPolicyFunc,
}
resp, err := client.Get("http://example.com")
// ...
req, err := http.NewRequest("GET", "http://example.com", nil)
// ...
req.Header.Add("If-None-Match", `W/"wyzzy"`)
resp, err := client.Do(req)
// ...
For control over proxies, TLS configuration, keep-alives, compression, and other settings, create a Transport:
tr := &http.Transport{
TLSClientConfig: &tls.Config{RootCAs: pool},
DisableCompression: true,
}
client := &http.Client{Transport: tr}
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:
http.Handle("/foo", fooHandler)
http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
})
log.Fatal(http.ListenAndServe(":8080", nil))
More control over the server's behavior is available by creating a custom Server:
s := &http.Server{
Addr: ":8080",
Handler: myHandler,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
log.Fatal(s.ListenAndServe())
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:
GODEBUG=http2client=0 # disable HTTP/2 client support GODEBUG=http2server=0 # disable HTTP/2 server support GODEBUG=http2debug=1 # enable verbose HTTP/2 debug logs GODEBUG=http2debug=2 # ... even more verbose, with frame dumps
The GODEBUG variables are not covered by Go's API compatibility promise. HTTP/2 support was added in Go 1.6. Please report any issues instead of disabling HTTP/2 support: https://golang.org/s/http2bug
Index ¶
- Constants
- Variables
- func CanonicalHeaderKey(s string) string
- func DetectContentType(data []byte) string
- func Error(w ResponseWriter, error string, code int)
- func Handle(pattern string, handler Handler)
- func HandleFunc(pattern string, handler func(ResponseWriter, *Request))
- func ListenAndServe(addr string, handler Handler) error
- func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error
- func MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser
- func NotFound(w ResponseWriter, r *Request)
- func ParseHTTPVersion(vers string) (major, minor int, ok bool)
- func ParseTime(text string) (t time.Time, err error)
- func ProxyFromEnvironment(req *Request) (*url.URL, error)
- func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error)
- func Redirect(w ResponseWriter, r *Request, urlStr string, code int)
- func Serve(l net.Listener, handler Handler) error
- func ServeContent(w ResponseWriter, req *Request, name string, modtime time.Time, ...)
- func ServeFile(w ResponseWriter, r *Request, name string)
- func SetCookie(w ResponseWriter, cookie *Cookie)
- func StatusText(code int) string
- type Client
- func (c *Client) Do(req *Request) (*Response, error)
- func (c *Client) Get(url string) (resp *Response, err error)
- func (c *Client) Head(url string) (resp *Response, err error)
- func (c *Client) Post(url string, bodyType string, body io.Reader) (resp *Response, err error)
- func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error)
- type CloseNotifier
- type ConnState
- type Cookie
- type CookieJar
- type Dir
- type File
- type FileSystem
- type Flusher
- type Handler
- type HandlerFunc
- type Header
- type Hijacker
- type ProtocolError
- type Request
- func (r *Request) AddCookie(c *Cookie)
- func (r *Request) BasicAuth() (username, password string, ok bool)
- func (r *Request) Context() context.Context
- func (r *Request) Cookie(name string) (*Cookie, error)
- func (r *Request) Cookies() []*Cookie
- func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error)
- func (r *Request) FormValue(key string) string
- func (r *Request) MultipartReader() (*multipart.Reader, error)
- func (r *Request) ParseForm() error
- func (r *Request) ParseMultipartForm(maxMemory int64) error
- func (r *Request) PostFormValue(key string) string
- func (r *Request) ProtoAtLeast(major, minor int) bool
- func (r *Request) Referer() string
- func (r *Request) SetBasicAuth(username, password string)
- func (r *Request) UserAgent() string
- func (r *Request) WithContext(ctx context.Context) *Request
- func (r *Request) Write(w io.Writer) error
- func (r *Request) WriteProxy(w io.Writer) error
- type Response
- func Get(url string) (resp *Response, err error)
- func Head(url string) (resp *Response, err error)
- func Post(url string, bodyType string, body io.Reader) (resp *Response, err error)
- func PostForm(url string, data url.Values) (resp *Response, err error)
- func ReadResponse(r *bufio.Reader, req *Request) (*Response, error)
- type ResponseWriter
- type RoundTripper
- type ServeMux
- type Server
- type Transport
Examples ¶
Constants ¶
const ( MethodGet = "GET" MethodHead = "HEAD" MethodPost = "POST" MethodPut = "PUT" MethodPatch = "PATCH" MethodDelete = "DELETE" MethodConnect = "CONNECT" MethodOptions = "OPTIONS" MethodTrace = "TRACE" )
Common HTTP methods.
Unless otherwise noted, these are defined in RFC 7231 section 4.3.
const ( StatusContinue = 100 StatusSwitchingProtocols = 101 StatusProcessing = 102 StatusOK = 200 StatusCreated = 201 StatusAccepted = 202 StatusNonAuthoritativeInfo = 203 StatusNoContent = 204 StatusResetContent = 205 StatusPartialContent = 206 StatusMultiStatus = 207 StatusAlreadyReported = 208 StatusIMUsed = 226 StatusMultipleChoices = 300 StatusMovedPermanently = 301 StatusFound = 302 StatusSeeOther = 303 StatusNotModified = 304 StatusUseProxy = 305 StatusTemporaryRedirect = 307 StatusPermanentRedirect = 308 StatusBadRequest = 400 StatusPaymentRequired = 402 StatusForbidden = 403 StatusNotFound = 404 StatusMethodNotAllowed = 405 StatusNotAcceptable = 406 StatusProxyAuthRequired = 407 StatusRequestTimeout = 408 StatusConflict = 409 StatusGone = 410 StatusLengthRequired = 411 StatusPreconditionFailed = 412 StatusRequestEntityTooLarge = 413 StatusRequestURITooLong = 414 StatusUnsupportedMediaType = 415 StatusRequestedRangeNotSatisfiable = 416 StatusExpectationFailed = 417 StatusTeapot = 418 StatusUnprocessableEntity = 422 StatusLocked = 423 StatusFailedDependency = 424 StatusUpgradeRequired = 426 StatusPreconditionRequired = 428 StatusTooManyRequests = 429 StatusRequestHeaderFieldsTooLarge = 431 StatusInternalServerError = 500 StatusNotImplemented = 501 StatusBadGateway = 502 StatusGatewayTimeout = 504 StatusHTTPVersionNotSupported = 505 StatusVariantAlsoNegotiates = 506 StatusInsufficientStorage = 507 StatusLoopDetected = 508 StatusNotExtended = 510 StatusNetworkAuthenticationRequired = 511 )
HTTP status codes as registered with IANA. See: http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const DefaultMaxHeaderBytes = 1 << 20
DefaultMaxHeaderBytes is the maximum permitted size of the headers in an HTTP request. This can be overridden by setting Server.MaxHeaderBytes.
const DefaultMaxIdleConnsPerHost = 2
DefaultMaxIdleConnsPerHost is the default value of Transport's MaxIdleConnsPerHost.
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.
Variables ¶
var ( ErrHeaderTooLong = &ProtocolError{"header too long"} ErrShortBody = &ProtocolError{"entity body too short"} ErrNotSupported = &ProtocolError{"feature not supported"} ErrUnexpectedTrailer = &ProtocolError{"trailer header without chunked transfer encoding"} ErrMissingContentLength = &ProtocolError{"missing ContentLength in HEAD response"} ErrNotMultipart = &ProtocolError{"request Content-Type isn't multipart/form-data"} ErrMissingBoundary = &ProtocolError{"no multipart boundary param in Content-Type"} )
var ( // ErrBodyNotAllowed is returned by ResponseWriter.Write calls // when the HTTP method or response code does not permit a // body. ErrBodyNotAllowed = errors.New("http: request method or response status code does not allow body") // ErrHijacked is returned by ResponseWriter.Write calls when // the underlying connection has been hijacked using the // Hijacker interfaced. ErrHijacked = errors.New("http: connection has been hijacked") // ErrContentLength is returned by ResponseWriter.Write calls // when a Handler set a Content-Length response header with a // declared size and then attempted to write more bytes than // declared. ErrContentLength = errors.New("http: wrote more than the declared Content-Length") // Deprecated: ErrWriteAfterFlush is no longer used. ErrWriteAfterFlush = errors.New("unused") )
Errors used by the HTTP server.
var ( // ServerContextKey is a context key. It can be used in HTTP // handlers with context.WithValue to access the server that // started the handler. The associated value will be of // type *Server. ServerContextKey = &contextKey{"http-server"} // LocalAddrContextKey is a context key. It can be used in // HTTP handlers with context.WithValue to access the address // the local address the connection arrived on. // The associated value will be of type net.Addr. LocalAddrContextKey = &contextKey{"local-addr"} )
var DefaultClient = &Client{}
DefaultClient is the default Client and is used by Get, Head, and Post.
var DefaultServeMux = &defaultServeMux
DefaultServeMux is the default ServeMux used by Serve.
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.
var ErrHandlerTimeout = errors.New("http: Handler timeout")
ErrHandlerTimeout is returned on ResponseWriter Write calls in handlers which have timed out.
var ErrLineTooLong = internal.ErrLineTooLong
ErrLineTooLong is returned when reading request or response bodies with malformed chunked encoding.
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.
var ErrNoCookie = errors.New("http: named cookie not present")
ErrNoCookie is returned by Request's Cookie method when a cookie is not found.
var ErrNoLocation = errors.New("http: no Location header in response")
ErrNoLocation is returned by Response's Location method when no Location header is present.
var ErrSkipAltProtocol = errors.New("net/http: skip alternate protocol")
ErrSkipAltProtocol is a sentinel error value defined by Transport.RegisterProtocol.
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.
Functions ¶
func CanonicalHeaderKey ¶
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 ¶
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 ¶
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 ¶
Handle registers the handler for the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched.
func HandleFunc ¶
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 ¶
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:
package main
import (
"io"
"net/http"
"log"
)
// hello world, the web server
func HelloServer(w http.ResponseWriter, req *http.Request) {
io.WriteString(w, "hello, world!\n")
}
func main() {
http.HandleFunc("/hello", HelloServer)
log.Fatal(http.ListenAndServe(":12345", nil))
}
ListenAndServe always returns a non-nil error.
func ListenAndServeTLS ¶
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:
import (
"log"
"net/http"
)
func handler(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("This is an example server.\n"))
}
func main() {
http.HandleFunc("/", handler)
log.Printf("About to listen on 10443. Go to https://127.0.0.1:10443/")
err := http.ListenAndServeTLS(":10443", "cert.pem", "key.pem", nil)
log.Fatal(err)
}
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 ¶
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 ¶
func NotFound(w ResponseWriter, r *Request)
NotFound replies to the request with an HTTP 404 not found error.
func ParseHTTPVersion ¶
ParseHTTPVersion parses a HTTP version string. "HTTP/1.0" returns (1, 0, true).
func ParseTime ¶ added in v1.1.0
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 ¶
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 ¶
ProxyURL returns a proxy function (for use in a Transport) that always returns the same URL.
func Redirect ¶
func Redirect(w ResponseWriter, r *Request, urlStr 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 ¶
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 ¶
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-Modified-Since 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, ServeContent uses it to handle requests using If-Range and If-None-Match.
Note that *os.File implements the io.ReadSeeker interface.
func ServeFile ¶
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 SetCookie ¶
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 ¶
StatusText returns a text for the HTTP status code. It returns the empty string if the code is unknown.
Types ¶
type Client ¶
type Client struct {
Transport RoundTripper
CheckRedirect func(req *Request, via []*Request) error
Jar CookieJar
Timeout time.Duration
}
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.
func (*Client) Do ¶
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.
func (*Client) Get ¶
Get issues a GET to the specified URL. If the response is one of the following redirect codes, Get follows the redirect after calling the Client's CheckRedirect function:
301 (Moved Permanently) 302 (Found) 303 (See Other) 307 (Temporary Redirect)
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 ¶
Head issues a HEAD to the specified URL. If the response is one of the following redirect codes, Head follows the redirect after calling the Client's CheckRedirect function:
301 (Moved Permanently) 302 (Found) 303 (See Other) 307 (Temporary Redirect)
func (*Client) Post ¶
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.
func (*Client) PostForm ¶
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.
type CloseNotifier ¶ added in v1.1.0
type CloseNotifier interface {
CloseNotify() <-chan bool
}
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 ¶ added in v1.3.0
type ConnState int
A ConnState represents the state of a client connection to a server. It's used by the optional Server.ConnState hook.
const ( // StateNew represents a new connection that is expected to // send a request immediately. Connections begin at this // state and then transition to either StateActive or // StateClosed. StateNew ConnState = iota // StateActive represents a connection that has read 1 or more // bytes of a request. The Server.ConnState hook for // StateActive fires before the request has entered a handler // and doesn't fire again until the request has been // handled. After the request is handled, the state // transitions to StateClosed, StateHijacked, or StateIdle. // For HTTP/2, StateActive fires on the transition from zero // to one active request, and only transitions away once all // active requests are complete. That means that ConnState // cannot be used to do per-request work; ConnState only notes // the overall state of the connection. StateActive // StateIdle represents a connection that has finished // handling a request and is in the keep-alive state, waiting // for a new request. Connections transition from StateIdle // to either StateActive or StateClosed. StateIdle // StateHijacked represents a hijacked connection. // This is a terminal state. It does not transition to StateClosed. StateHijacked // StateClosed represents a closed connection. // This is a terminal state. Hijacked connections do not // transition to StateClosed. StateClosed )
type Cookie ¶
type Cookie struct {
Name string
Value string
Path string
Domain string
Expires time.Time
RawExpires string
MaxAge int
Secure bool
HttpOnly bool
Raw string
Unparsed []string
}
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.
type CookieJar ¶
type CookieJar interface {
SetCookies(u *url.URL, cookies []*Cookie)
Cookies(u *url.URL) []*Cookie
}
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 ¶
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 '/'.
An empty Dir is treated as ".".
type File ¶
type File interface {
io.Closer
io.Reader
io.Seeker
Readdir(count int) ([]os.FileInfo, error)
Stat() (os.FileInfo, error)
}
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 ¶
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 ¶
type Flusher interface {
Flush()
}
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 ¶
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}
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 hangs up the connection.
func FileServer ¶
func FileServer(root FileSystem) Handler
FileServer returns a handler that serves HTTP requests with the contents of the file system rooted at root.
To use the operating system's file system implementation, use http.Dir:
http.Handle("/", http.FileServer(http.Dir("/tmp")))
As a special case, the returned file server redirects any request ending in "/index.html" to the same path, without the final "index.html".
Example ¶
package main
import (
"log"
"net/http"
)
func main() {
// Simple static webserver:
log.Fatal(http.ListenAndServe(":8080", http.FileServer(http.Dir("/usr/share/doc"))))
}
Output:
Example (StripPrefix) ¶
package main
import (
"net/http"
)
func main() {
// To serve a directory on disk (/tmp) under an alternate URL
// path (/tmpfiles/), use StripPrefix to modify the request
// URL's path before the FileServer sees it:
http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
}
Output:
func NotFoundHandler ¶
func NotFoundHandler() Handler
NotFoundHandler returns a simple request handler that replies to each request with a “404 page not found” reply.
func RedirectHandler ¶
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 ¶
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 ¶
package main
import (
"net/http"
)
func main() {
// To serve a directory on disk (/tmp) under an alternate URL
// path (/tmpfiles/), use StripPrefix to modify the request
// URL's path before the FileServer sees it:
http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
}
Output:
func TimeoutHandler ¶
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 ¶
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 ¶
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request)
ServeHTTP calls f(w, r).
type Header ¶
A Header represents the key-value pairs in an HTTP header.
func (Header) Add ¶
Add adds the key, value pair to the header. It appends to any existing values associated with key.
func (Header) Get ¶
Get gets the first value associated with the given key. If there are no values associated with the key, Get returns "". To access multiple values of a key, access the map directly with CanonicalHeaderKey.
func (Header) Set ¶
Set sets the header entries associated with key to the single element value. It replaces any existing values associated with key.
type Hijacker ¶
type Hijacker interface {
Hijack() (net.Conn, *bufio.ReadWriter, error)
}
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 ¶
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/hijack", func(w http.ResponseWriter, r *http.Request) {
hj, ok := w.(http.Hijacker)
if !ok {
http.Error(w, "webserver doesn't support hijacking", http.StatusInternalServerError)
return
}
conn, bufrw, err := hj.Hijack()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Don't forget to close the connection:
defer conn.Close()
bufrw.WriteString("Now we're speaking raw TCP. Say hi: ")
bufrw.Flush()
s, err := bufrw.ReadString('\n')
if err != nil {
log.Printf("error reading string: %v", err)
return
}
fmt.Fprintf(bufrw, "You said: %q\nBye.\n", s)
bufrw.Flush()
})
}
Output:
type ProtocolError ¶
type ProtocolError struct {
ErrorString string
}
HTTP request parsing errors.
func (*ProtocolError) Error ¶
func (err *ProtocolError) Error() string
type Request ¶
type Request struct {
Method string
URL *url.URL
Proto string
ProtoMajor int
ProtoMinor int
Header Header
Body io.ReadCloser
ContentLength int64
TransferEncoding []string
Close bool
Host string
Form url.Values
PostForm url.Values
MultipartForm *multipart.Form
Trailer Header
RemoteAddr string
RequestURI string
TLS *tls.ConnectionState
Cancel <-chan struct{}
Response *Response
// contains filtered or unexported fields
}
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 ¶
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 use either ReadRequest or manually update the Request fields. See the Request type's documentation for the difference between inbound and outbound request fields.
func ReadRequest ¶
ReadRequest reads and parses an incoming request from b.
func (*Request) AddCookie ¶
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 ¶ added in v1.4.0
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 ¶ added in v1.7.0
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 ServeHTTP method returns. For its associated values, see ServerContextKey and LocalAddrContextKey.
func (*Request) Cookie ¶
Cookie returns the named cookie provided in the request or ErrNoCookie if not found.
func (*Request) FormFile ¶
FormFile returns the first file for the provided form key. FormFile calls ParseMultipartForm and ParseForm if necessary.
func (*Request) FormValue ¶
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 ¶
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 ¶
ParseForm parses the raw query from the URL and updates r.Form.
For POST or PUT requests, it also parses the request body as a form and put the results into both r.PostForm and r.Form. POST and PUT body parameters take precedence over URL query string values in r.Form.
If the request Body's size has not already been limited by MaxBytesReader, the size is capped at 10MB.
ParseMultipartForm calls ParseForm automatically. It is idempotent.
func (*Request) ParseMultipartForm ¶
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 ¶ added in v1.1.0
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 ¶
ProtoAtLeast reports whether the HTTP protocol used in the request is at least major.minor.
func (*Request) Referer ¶
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 ¶
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) WithContext ¶ added in v1.7.0
WithContext returns a shallow copy of r with its context changed to ctx. The provided ctx must be non-nil.
func (*Request) Write ¶
Write writes an HTTP/1.1 request, which is the header and body, in wire format. This method consults the following fields of the request:
Host URL Method (defaults to "GET") Header ContentLength TransferEncoding Body
If Body is present, Content-Length is <= 0 and TransferEncoding hasn't been set to "identity", Write adds "Transfer-Encoding: chunked" to the header. Body is closed after it is sent.
func (*Request) WriteProxy ¶
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 ¶
type Response struct {
Status string
StatusCode int
Proto string
ProtoMajor int
ProtoMinor int
Header Header
Body io.ReadCloser
ContentLength int64
TransferEncoding []string
Close bool
Uncompressed bool
Trailer Header
Request *Request
TLS *tls.ConnectionState
}
Response represents the response from an HTTP request.
func Get ¶
Get issues a GET to the specified URL. If the response is one of the following redirect codes, Get follows the redirect, up to a maximum of 10 redirects:
301 (Moved Permanently) 302 (Found) 303 (See Other) 307 (Temporary Redirect)
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 ¶
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
)
func main() {
res, err := http.Get("http://www.google.com/robots.txt")
if err != nil {
log.Fatal(err)
}
robots, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s", robots)
}
Output:
func Head ¶
Head issues a HEAD to the specified URL. If the response is one of the following redirect codes, Head follows the redirect, up to a maximum of 10 redirects:
301 (Moved Permanently) 302 (Found) 303 (See Other) 307 (Temporary Redirect)
Head is a wrapper around DefaultClient.Head
func Post ¶
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.
func PostForm ¶
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.
func ReadResponse ¶
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) Location ¶
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 ¶
ProtoAtLeast reports whether the HTTP protocol used in the response is at least major.minor.
func (*Response) Write ¶
Write writes r to w in the HTTP/1.x server response format, including the status line, headers, body, and optional trailer.
This method consults the following fields of the response r:
StatusCode ProtoMajor ProtoMinor Request.Method TransferEncoding Trailer Body ContentLength Header, values for non-canonical keys will have unpredictable behavior
The Response Body is closed after it is sent.
type ResponseWriter ¶
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 (Trailers) ¶
HTTP Trailers are a set of key/value pairs like headers that come after the HTTP response, instead of before.
package main
import (
"io"
"net/http"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/sendstrailers", func(w http.ResponseWriter, req *http.Request) {
// Before any call to WriteHeader or Write, declare
// the trailers you will set during the HTTP
// response. These three headers are actually sent in
// the trailer.
w.Header().Set("Trailer", "AtEnd1, AtEnd2")
w.Header().Add("Trailer", "AtEnd3")
w.Header().Set("Content-Type", "text/plain; charset=utf-8") // normal header
w.WriteHeader(http.StatusOK)
w.Header().Set("AtEnd1", "value 1")
io.WriteString(w, "This HTTP response has both headers before this text and trailers at the end.\n")
w.Header().Set("AtEnd2", "value 2")
w.Header().Set("AtEnd3", "value 3") // These will appear as trailers.
})
}
Output:
type RoundTripper ¶
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.
var DefaultTransport RoundTripper = &Transport{ Proxy: ProxyFromEnvironment, DialContext: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, }).DialContext, MaxIdleConns: 100, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, }
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 ¶
func NewFileTransport(fs FileSystem) RoundTripper
NewFileTransport returns a new RoundTripper, serving the provided FileSystem. The returned RoundTripper ignores the URL host in its incoming requests, as well as most other properties of the request.
The typical use case for NewFileTransport is to register the "file" protocol with a Transport, as in:
t := &http.Transport{}
t.RegisterProtocol("file", http.NewFileTransport(http.Dir("/")))
c := &http.Client{Transport: t}
res, err := c.Get("file:///etc/passwd")
...
type ServeMux ¶
type ServeMux struct {
// contains filtered or unexported fields
}
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 (*ServeMux) Handle ¶
Handle registers the handler for the given pattern. If a handler already exists for pattern, Handle panics.
Example ¶
mux := http.NewServeMux()
mux.Handle("/api/", apiHandler{})
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
// The "/" pattern matches everything, so we need to check
// that we're at the root here.
if req.URL.Path != "/" {
http.NotFound(w, req)
return
}
fmt.Fprintf(w, "Welcome to the home page!")
})
func (*ServeMux) HandleFunc ¶
func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))
HandleFunc registers the handler function for the given pattern.
func (*ServeMux) Handler ¶ added in v1.1.0
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.
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 ¶
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 ¶
type Server struct {
Addr string
Handler Handler
ReadTimeout time.Duration
WriteTimeout time.Duration
TLSConfig *tls.Config
MaxHeaderBytes int
TLSNextProto map[string]func(*Server, *tls.Conn, Handler)
ConnState func(net.Conn, ConnState)
ErrorLog *log.Logger
// contains filtered or unexported fields
}
A Server defines parameters for running an HTTP server. The zero value for Server is a valid configuration.
func (*Server) ListenAndServe ¶
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 ¶
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) Serve ¶
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.
func (*Server) SetKeepAlivesEnabled ¶ added in v1.3.0
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.
type Transport ¶
type Transport struct {
Proxy func(*Request) (*url.URL, error)
DialContext func(ctx context.Context, network, addr string) (net.Conn, error)
Dial func(network, addr string) (net.Conn, error)
DialTLS func(network, addr string) (net.Conn, error)
TLSClientConfig *tls.Config
TLSHandshakeTimeout time.Duration
DisableKeepAlives bool
DisableCompression bool
MaxIdleConns int
MaxIdleConnsPerHost int
IdleConnTimeout time.Duration
ResponseHeaderTimeout time.Duration
ExpectContinueTimeout time.Duration
TLSNextProto map[string]func(authority string, c *tls.Conn) RoundTripper
MaxResponseHeaderBytes int64
// contains filtered or unexported fields
}
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. See the package docs for more about HTTP/2.
func (*Transport) CancelRequest
deprecated
added in
v1.1.0
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 ¶
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 ¶
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.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package cgi implements CGI (Common Gateway Interface) as specified in RFC 3875.
|
Package cgi implements CGI (Common Gateway Interface) as specified in RFC 3875. |
|
Package cookiejar implements an in-memory RFC 6265-compliant http.CookieJar.
|
Package cookiejar implements an in-memory RFC 6265-compliant http.CookieJar. |
|
Package fcgi implements the FastCGI protocol.
|
Package fcgi implements the FastCGI protocol. |
|
Package httptest provides utilities for HTTP testing.
|
Package httptest provides utilities for HTTP testing. |
|
Package httptrace provides mechanisms to trace the events within HTTP client requests.
|
Package httptrace provides mechanisms to trace the events within HTTP client requests. |
|
Package httputil provides HTTP utility functions, complementing the more common ones in the net/http package.
|
Package httputil provides HTTP utility functions, complementing the more common ones in the net/http package. |
|
Package pprof serves via its HTTP server runtime profiling data in the format expected by the pprof visualization tool.
|
Package pprof serves via its HTTP server runtime profiling data in the format expected by the pprof visualization tool. |