Movatterモバイル変換


[0]ホーム

URL:


http

packagestandard library
go1.25.4Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 5, 2025 License:BSD-3-ClauseImports:47Imported by:1,705,800

Details

Repository

cs.opensource.google/go/go

Links

Documentation

Overview

Package http provides HTTP client and server implementations.

Get,Head,Post, andPostForm 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 caller 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 := io.ReadAll(resp.Body)// ...

Clients and Transports

For control over HTTP client headers, redirect policy, and othersettings, create aClient:

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 aTransport:

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

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

Servers

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

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 acustom Server:

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

HTTP/2

Starting with Go 1.6, the http package has transparent support for theHTTP/2 protocol when using HTTPS. Programs that must disable HTTP/2can do so by setting [Transport.TLSNextProto] (for clients) or[Server.TLSNextProto] (for servers) to a non-nil, emptymap. Alternatively, the following GODEBUG settings arecurrently supported:

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

Please report any issues before disabling HTTP/2 support:https://golang.org/s/http2bug

The http package'sTransport andServer both automatically enableHTTP/2 support for simple configurations. To enable HTTP/2 for morecomplex configurations, to use lower-level HTTP/2 features, or to usea newer version of Go's http2 package, import "golang.org/x/net/http2"directly and use its ConfigureTransport and/or ConfigureServerfunctions. Manually configuring HTTP/2 via the golang.org/x/net/http2package takes precedence over the net/http package's built-in HTTP/2support.

Index

Examples

Constants

View Source
const (MethodGet     = "GET"MethodHead    = "HEAD"MethodPost    = "POST"MethodPut     = "PUT"MethodPatch   = "PATCH"//RFC 5789MethodDelete  = "DELETE"MethodConnect = "CONNECT"MethodOptions = "OPTIONS"MethodTrace   = "TRACE")

Common HTTP methods.

Unless otherwise noted, these are defined inRFC 7231 section 4.3.

View Source
const (StatusContinue           = 100//RFC 9110, 15.2.1StatusSwitchingProtocols = 101//RFC 9110, 15.2.2StatusProcessing         = 102//RFC 2518, 10.1StatusEarlyHints         = 103//RFC 8297StatusOK                   = 200//RFC 9110, 15.3.1StatusCreated              = 201//RFC 9110, 15.3.2StatusAccepted             = 202//RFC 9110, 15.3.3StatusNonAuthoritativeInfo = 203//RFC 9110, 15.3.4StatusNoContent            = 204//RFC 9110, 15.3.5StatusResetContent         = 205//RFC 9110, 15.3.6StatusPartialContent       = 206//RFC 9110, 15.3.7StatusMultiStatus          = 207//RFC 4918, 11.1StatusAlreadyReported      = 208//RFC 5842, 7.1StatusIMUsed               = 226//RFC 3229, 10.4.1StatusMultipleChoices  = 300//RFC 9110, 15.4.1StatusMovedPermanently = 301//RFC 9110, 15.4.2StatusFound            = 302//RFC 9110, 15.4.3StatusSeeOther         = 303//RFC 9110, 15.4.4StatusNotModified      = 304//RFC 9110, 15.4.5StatusUseProxy         = 305//RFC 9110, 15.4.6StatusTemporaryRedirect = 307//RFC 9110, 15.4.8StatusPermanentRedirect = 308//RFC 9110, 15.4.9StatusBadRequest                   = 400//RFC 9110, 15.5.1StatusUnauthorized                 = 401//RFC 9110, 15.5.2StatusPaymentRequired              = 402//RFC 9110, 15.5.3StatusForbidden                    = 403//RFC 9110, 15.5.4StatusNotFound                     = 404//RFC 9110, 15.5.5StatusMethodNotAllowed             = 405//RFC 9110, 15.5.6StatusNotAcceptable                = 406//RFC 9110, 15.5.7StatusProxyAuthRequired            = 407//RFC 9110, 15.5.8StatusRequestTimeout               = 408//RFC 9110, 15.5.9StatusConflict                     = 409//RFC 9110, 15.5.10StatusGone                         = 410//RFC 9110, 15.5.11StatusLengthRequired               = 411//RFC 9110, 15.5.12StatusPreconditionFailed           = 412//RFC 9110, 15.5.13StatusRequestEntityTooLarge        = 413//RFC 9110, 15.5.14StatusRequestURITooLong            = 414//RFC 9110, 15.5.15StatusUnsupportedMediaType         = 415//RFC 9110, 15.5.16StatusRequestedRangeNotSatisfiable = 416//RFC 9110, 15.5.17StatusExpectationFailed            = 417//RFC 9110, 15.5.18StatusTeapot                       = 418//RFC 9110, 15.5.19 (Unused)StatusMisdirectedRequest           = 421//RFC 9110, 15.5.20StatusUnprocessableEntity          = 422//RFC 9110, 15.5.21StatusLocked                       = 423//RFC 4918, 11.3StatusFailedDependency             = 424//RFC 4918, 11.4StatusTooEarly                     = 425//RFC 8470, 5.2.StatusUpgradeRequired              = 426//RFC 9110, 15.5.22StatusPreconditionRequired         = 428//RFC 6585, 3StatusTooManyRequests              = 429//RFC 6585, 4StatusRequestHeaderFieldsTooLarge  = 431//RFC 6585, 5StatusUnavailableForLegalReasons   = 451//RFC 7725, 3StatusInternalServerError           = 500//RFC 9110, 15.6.1StatusNotImplemented                = 501//RFC 9110, 15.6.2StatusBadGateway                    = 502//RFC 9110, 15.6.3StatusServiceUnavailable            = 503//RFC 9110, 15.6.4StatusGatewayTimeout                = 504//RFC 9110, 15.6.5StatusHTTPVersionNotSupported       = 505//RFC 9110, 15.6.6StatusVariantAlsoNegotiates         = 506//RFC 2295, 8.1StatusInsufficientStorage           = 507//RFC 4918, 11.5StatusLoopDetected                  = 508//RFC 5842, 7.2StatusNotExtended                   = 510//RFC 2774, 7StatusNetworkAuthenticationRequired = 511//RFC 6585, 6)

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

View Source
const DefaultMaxHeaderBytes = 1 << 20// 1 MB

DefaultMaxHeaderBytes is the maximum permitted size of the headersin an HTTP request.This can be overridden by setting [Server.MaxHeaderBytes].

View Source
const DefaultMaxIdleConnsPerHost = 2

DefaultMaxIdleConnsPerHost is the default value ofTransport'sMaxIdleConnsPerHost.

View Source
const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"

TimeFormat is the time format to use when generating times in HTTPheaders. It is liketime.RFC1123 but hard-codes GMT as the timezone. The time being formatted must be in UTC for Format togenerate the correct format.

For parsing this time format, seeParseTime.

View Source
const TrailerPrefix = "Trailer:"

TrailerPrefix is a magic prefix for [ResponseWriter.Header] map keysthat, if present, signals that the map entry is actually forthe response trailers, and not the response headers. The prefixis stripped after the ServeHTTP call finishes and the values aresent in the trailers.

This mechanism is intended only for trailers that are not knownprior to the headers being written. If the set of trailers is fixedor known before the header is written, the normal Go trailers mechanismis preferred:

https://pkg.go.dev/net/http#ResponseWriterhttps://pkg.go.dev/net/http#example-ResponseWriter-Trailers

Variables

View Source
var (// ErrNotSupported indicates that a feature is not supported.//// It is returned by ResponseController methods to indicate that// the handler does not support the method, and by the Push method// of Pusher implementations to indicate that HTTP/2 Push support// is not available.ErrNotSupported = &ProtocolError{"feature not supported"}// Deprecated: ErrUnexpectedTrailer is no longer returned by// anything in the net/http package. Callers should not// compare errors against this variable.ErrUnexpectedTrailer = &ProtocolError{"trailer header without chunked transfer encoding"}// ErrMissingBoundary is returned by Request.MultipartReader when the// request's Content-Type does not include a "boundary" parameter.ErrMissingBoundary = &ProtocolError{"no multipart boundary param in Content-Type"}// ErrNotMultipart is returned by Request.MultipartReader when the// request's Content-Type is not multipart/form-data.ErrNotMultipart = &ProtocolError{"request Content-Type isn't multipart/form-data"}// Deprecated: ErrHeaderTooLong is no longer returned by// anything in the net/http package. Callers should not// compare errors against this variable.ErrHeaderTooLong = &ProtocolError{"header too long"}// Deprecated: ErrShortBody is no longer returned by// anything in the net/http package. Callers should not// compare errors against this variable.ErrShortBody = &ProtocolError{"entity body too short"}// Deprecated: ErrMissingContentLength is no longer returned by// anything in the net/http package. Callers should not// compare errors against this variable.ErrMissingContentLength = &ProtocolError{"missing ContentLength in HEAD response"})
View Source
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 interface. A zero-byte write on a hijacked// connection will return ErrHijacked without any other side// effects.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 returned by// anything in the net/http package. Callers should not// compare errors against this variable.ErrWriteAfterFlush =errors.New("unused"))

Errors used by the HTTP server.

View Source
var (// ServerContextKey is a context key. It can be used in HTTP// handlers with Context.Value to access the server that// started the handler. The associated value will be of// type *Server.ServerContextKey = &contextKey{"http-server"}// LocalAddrContextKey is a context key. It can be used in// HTTP handlers with Context.Value to access the local// address the connection arrived on.// The associated value will be of type net.Addr.LocalAddrContextKey = &contextKey{"local-addr"})
View Source
var DefaultClient = &Client{}

DefaultClient is the defaultClient and is used byGet,Head, andPost.

View Source
var DefaultServeMux = &defaultServeMux

DefaultServeMux is the defaultServeMux used byServe.

View Source
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 stacktrace to the server's error log.

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

ErrBodyReadAfterClose is returned when reading aRequest orResponseBody after the body has been closed. This typically happens when the body isread after an HTTPHandler calls WriteHeader or Write on itsResponseWriter.

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

ErrHandlerTimeout is returned onResponseWriter Write callsin handlers which have timed out.

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

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

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

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

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

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

ErrNoLocation is returned by theResponse.Location methodwhen no Location header is present.

View Source
var ErrSchemeMismatch =errors.New("http: server gave HTTP response to HTTPS client")

ErrSchemeMismatch is returned when a server returns an HTTP response to an HTTPS client.

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

ErrServerClosed is returned by theServer.Serve,ServeTLS,ListenAndServe,andListenAndServeTLS methods after a call toServer.Shutdown orServer.Close.

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

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

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

ErrUseLastResponse can be returned by Client.CheckRedirect hooks tocontrol how redirects are processed. If returned, the next requestis not sent and the most recent response is returned with its bodyunclosed.

View Source
var NoBody = noBody{}

NoBody is anio.ReadCloser with no bytes. Read always returns EOFand Close always returns nil. It can be used in an outgoing clientrequest to explicitly signal that a request has zero bytes.An alternative, however, is to simply set [Request.Body] to nil.

Functions

funcCanonicalHeaderKey

func CanonicalHeaderKey(sstring)string

CanonicalHeaderKey returns the canonical format of theheader key s. The canonicalization converts the firstletter and any letter following a hyphen to upper case;the rest are converted to lowercase. For example, thecanonical key for "accept-encoding" is "Accept-Encoding".If s contains a space or invalid header field bytes, it isreturned without modifications.

funcDetectContentType

func DetectContentType(data []byte)string

DetectContentType implements the algorithm describedathttps://mimesniff.spec.whatwg.org/ to determine theContent-Type of the given data. It considers at most thefirst 512 bytes of data. DetectContentType always returnsa valid MIME type: if it cannot determine a more specific one, itreturns "application/octet-stream".

funcError

func Error(wResponseWriter, errorstring, codeint)

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 furtherwrites are done to w.The error message should be plain text.

Error deletes the Content-Length header,sets Content-Type to “text/plain; charset=utf-8”,and sets X-Content-Type-Options to “nosniff”.This configures the header properly for the error message,in case the caller had set it up expecting a successful output.

funcHandle

func Handle(patternstring, handlerHandler)

Handle registers the handler for the given pattern inDefaultServeMux.The documentation forServeMux explains how patterns are matched.

Example
package mainimport ("fmt""log""net/http""sync")type countHandler struct {mu sync.Mutex // guards nn  int}func (h *countHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {h.mu.Lock()defer h.mu.Unlock()h.n++fmt.Fprintf(w, "count is %d\n", h.n)}func main() {http.Handle("/count", new(countHandler))log.Fatal(http.ListenAndServe(":8080", nil))}

funcHandleFunc

func HandleFunc(patternstring, handler func(ResponseWriter, *Request))

HandleFunc registers the handler function for the given pattern inDefaultServeMux.The documentation forServeMux explains how patterns are matched.

Example
package mainimport ("io""log""net/http")func main() {h1 := func(w http.ResponseWriter, _ *http.Request) {io.WriteString(w, "Hello from a HandleFunc #1!\n")}h2 := func(w http.ResponseWriter, _ *http.Request) {io.WriteString(w, "Hello from a HandleFunc #2!\n")}http.HandleFunc("/", h1)http.HandleFunc("/endpoint", h2)log.Fatal(http.ListenAndServe(":8080", nil))}

funcListenAndServe

func ListenAndServe(addrstring, handlerHandler)error

ListenAndServe listens on the TCP network address addr and then callsServe with handler to handle requests on incoming connections.Accepted connections are configured to enable TCP keep-alives.

The handler is typically nil, in which caseDefaultServeMux is used.

ListenAndServe always returns a non-nil error.

Example
package mainimport ("io""log""net/http")func main() {// Hello world, the web serverhelloHandler := func(w http.ResponseWriter, req *http.Request) {io.WriteString(w, "Hello, world!\n")}http.HandleFunc("/hello", helloHandler)log.Fatal(http.ListenAndServe(":8080", nil))}

funcListenAndServeTLS

func ListenAndServeTLS(addr, certFile, keyFilestring, handlerHandler)error

ListenAndServeTLS acts identically toListenAndServe, except that itexpects HTTPS connections. Additionally, files containing a certificate andmatching private key for the server must be provided. If the certificateis signed by a certificate authority, the certFile should be the concatenationof the server's certificate, any intermediates, and the CA's certificate.

Example
package mainimport ("io""log""net/http")func main() {http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {io.WriteString(w, "Hello, TLS!\n")})// One can use generate_cert.go in crypto/tls to generate cert.pem and key.pem.log.Printf("About to listen on 8443. Go to https://127.0.0.1:8443/")err := http.ListenAndServeTLS(":8443", "cert.pem", "key.pem", nil)log.Fatal(err)}

funcMaxBytesReader

func MaxBytesReader(wResponseWriter, rio.ReadCloser, nint64)io.ReadCloser

MaxBytesReader is similar toio.LimitReader but is intended forlimiting the size of incoming request bodies. In contrast toio.LimitReader, MaxBytesReader's result is a ReadCloser, returns anon-nil error of type*MaxBytesError for a Read beyond the limit,and closes the underlying reader when its Close method is called.

MaxBytesReader prevents clients from accidentally or maliciouslysending a large request and wasting server resources. If possible,it tells theResponseWriter to close the connection after the limithas been reached.

funcNotFound

func NotFound(wResponseWriter, r *Request)

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

funcParseHTTPVersion

func ParseHTTPVersion(versstring) (major, minorint, okbool)

ParseHTTPVersion parses an HTTP version string according toRFC 7230, section 2.6."HTTP/1.0" returns (1, 0, true). Note that strings withouta minor version, such as "HTTP/2", are not valid.

funcParseTimeadded ingo1.1

func ParseTime(textstring) (ttime.Time, errerror)

ParseTime parses a time header (such as the Date: header),trying each of the three formats allowed by HTTP/1.1:TimeFormat,time.RFC850, andtime.ANSIC.

funcProxyFromEnvironment

func ProxyFromEnvironment(req *Request) (*url.URL,error)

ProxyFromEnvironment returns the URL of the proxy to use for agiven request, as indicated by the environment variablesHTTP_PROXY, HTTPS_PROXY and NO_PROXY (or the lowercase versionsthereof). Requests use the proxy from the environment variablematching their scheme, unless excluded by NO_PROXY.

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 theenvironment, 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 withouta port number), then a nil URL and nil error will be returned.

funcProxyURL

func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL,error)

ProxyURL returns a proxy function (for use in aTransport)that always returns the same URL.

funcRedirect

func Redirect(wResponseWriter, r *Request, urlstring, codeint)

Redirect replies to the request with a redirect to url,which may be a path relative to the request path.Any non-ASCII characters in url will be percent-encoded,but existing percent encodings will not be changed.

The provided code should be in the 3xx range and is usuallyStatusMovedPermanently,StatusFound orStatusSeeOther.

If the Content-Type header has not been set,Redirect sets itto "text/html; charset=utf-8" and writes a small HTML body.Setting the Content-Type header to any value, including nil,disables that behavior.

funcServe

func Serve(lnet.Listener, handlerHandler)error

Serve accepts incoming HTTP connections on the listener l,creating a new service goroutine for each. The service goroutinesread requests and then call handler to reply to them.

The handler is typically nil, in which caseDefaultServeMux is used.

HTTP/2 support is only enabled if the Listener returns*tls.Connconnections and they were configured with "h2" in the TLSConfig.NextProtos.

Serve always returns a non-nil error.

funcServeContent

func ServeContent(wResponseWriter, req *Request, namestring, modtimetime.Time, contentio.ReadSeeker)

ServeContent replies to the request using the content in theprovided ReadSeeker. The main benefit of ServeContent overio.Copyis that it handles Range requests properly, sets the MIME type, andhandles 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, ServeContentfirst tries to deduce the type from name's file extension and,if that fails, falls back to reading the first block of the contentand passing it toDetectContentType.The name is otherwise unused; in particular it can be empty and isnever sent in the response.

If modtime is not the zero time or Unix epoch, ServeContentincludes it in a Last-Modified header in the response. If therequest includes an If-Modified-Since header, ServeContent usesmodtime to decide whether the content needs to be sent at all.

The content's Seek method must work: ServeContent usesa seek to the end of the content to determine its size.Note that*os.File implements theio.ReadSeeker interface.

If the caller has set w's ETag header formatted perRFC 7232, section 2.3,ServeContent uses it to handle requests using If-Match, If-None-Match, or If-Range.

If an error occurs when serving the request (for example, whenhandling an invalid range request), ServeContent responds with anerror message. By default, ServeContent strips the Cache-Control,Content-Encoding, ETag, and Last-Modified headers from error responses.The GODEBUG setting httpservecontentkeepheaders=1 causes ServeContentto preserve these headers.

funcServeFile

func ServeFile(wResponseWriter, r *Request, namestring)

ServeFile replies to the request with the contents of the namedfile or directory.

If the provided file or directory name is a relative path, it isinterpreted relative to the current directory and may ascend toparent directories. If the provided name is constructed from userinput, it should be sanitized before callingServeFile.

As a precaution, ServeFile will reject requests where r.URL.Pathcontains a ".." path element; this protects against callers whomight unsafely usefilepath.Join on r.URL.Path without sanitizingit and then use that filepath.Join result as the name argument.

As another special case, ServeFile redirects any request where r.URL.Pathends in "/index.html" to the same path, without the final"index.html". To avoid such redirects either modify the path oruseServeContent.

Outside of those two special cases, ServeFile does not user.URL.Path for selecting the file or directory to serve; only thefile or directory provided in the name argument is used.

funcServeFileFSadded ingo1.22.0

func ServeFileFS(wResponseWriter, r *Request, fsysfs.FS, namestring)

ServeFileFS replies to the request with the contentsof the named file or directory from the file system fsys.The files provided by fsys must implementio.Seeker.

If the provided name is constructed from user input, it should besanitized before callingServeFileFS.

As a precaution, ServeFileFS will reject requests where r.URL.Pathcontains a ".." path element; this protects against callers whomight unsafely usefilepath.Join on r.URL.Path without sanitizingit and then use that filepath.Join result as the name argument.

As another special case, ServeFileFS redirects any request where r.URL.Pathends in "/index.html" to the same path, without the final"index.html". To avoid such redirects either modify the path oruseServeContent.

Outside of those two special cases, ServeFileFS does not user.URL.Path for selecting the file or directory to serve; only thefile or directory provided in the name argument is used.

funcServeTLSadded ingo1.9

func ServeTLS(lnet.Listener, handlerHandler, certFile, keyFilestring)error

ServeTLS accepts incoming HTTPS connections on the listener l,creating a new service goroutine for each. The service goroutinesread requests and then call handler to reply to them.

The handler is typically nil, in which caseDefaultServeMux is used.

Additionally, files containing a certificate and matching private keyfor the server must be provided. If the certificate is signed by acertificate authority, the certFile should be the concatenationof the server's certificate, any intermediates, and the CA's certificate.

ServeTLS always returns a non-nil error.

funcSetCookie

func SetCookie(wResponseWriter, cookie *Cookie)

SetCookie adds a Set-Cookie header to the providedResponseWriter's headers.The provided cookie must have a valid Name. Invalid cookies may besilently dropped.

funcStatusText

func StatusText(codeint)string

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

Types

typeClient

type Client struct {// Transport specifies the mechanism by which individual// HTTP requests are made.// If nil, DefaultTransport is used.TransportRoundTripper// CheckRedirect specifies the policy for handling redirects.// If CheckRedirect is not nil, the client calls it before// following an HTTP redirect. The arguments req and via are// the upcoming request and the requests made already, oldest// first. If CheckRedirect returns an error, the Client's Get// method returns both the previous Response (with its Body// closed) and CheckRedirect's error (wrapped in a url.Error)// instead of issuing the Request req.// As a special case, if CheckRedirect returns ErrUseLastResponse,// then the most recent response is returned with its body// unclosed, along with a nil error.//// If CheckRedirect is nil, the Client uses its default policy,// which is to stop after 10 consecutive requests.CheckRedirect func(req *Request, via []*Request)error// Jar specifies the cookie jar.//// The Jar is used to insert relevant cookies into every// outbound Request and is updated with the cookie values// of every inbound Response. The Jar is consulted for every// redirect that the Client follows.//// If Jar is nil, cookies are only sent if they are explicitly// set on the Request.JarCookieJar// Timeout specifies a time limit for requests made by this// Client. The timeout includes connection time, any// redirects, and reading the response body. The timer remains// running after Get, Head, Post, or Do return and will// interrupt reading of the Response.Body.//// A Timeout of zero means no timeout.//// The Client cancels requests to the underlying Transport// as if the Request's Context ended.//// For compatibility, the Client will also use the deprecated// CancelRequest method on Transport if found. New// RoundTripper implementations should use the Request's Context// for cancellation instead of implementing CancelRequest.Timeouttime.Duration}

A Client is an HTTP client. Its zero value (DefaultClient) is ausable client that usesDefaultTransport.

The [Client.Transport] typically has internal state (cached TCPconnections), so Clients should be reused instead of created asneeded. Clients are safe for concurrent use by multiple goroutines.

A Client is higher-level than aRoundTripper (such asTransport)and additionally handles HTTP details such as cookies andredirects.

When following redirects, the Client will forward all headers set on theinitialRequest 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 domainthat 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 cookieswith the updated values (assuming the origin matches).If Jar is nil, the initial cookies are forwarded without change.

func (*Client)CloseIdleConnectionsadded ingo1.12

func (c *Client) CloseIdleConnections()

CloseIdleConnections closes any connections on itsTransport whichwere previously connected from previous requests but are nowsitting idle in a "keep-alive" state. It does not interrupt anyconnections currently in use.

If [Client.Transport] does not have aClient.CloseIdleConnections methodthen this method does nothing.

func (*Client)Do

func (c *Client) Do(req *Request) (*Response,error)

Do sends an HTTP request and returns an HTTP response, followingpolicy (such as redirects, cookies, auth) as configured on theclient.

An error is returned if caused by client policy (such asCheckRedirect), or failure to speak HTTP (such as a networkconnectivity problem). A non-2xx status code doesn't cause anerror.

If the returned error is nil, theResponse will contain a non-nilBody which the user is expected to close. If the Body is not bothread to EOF and closed, theClient's underlyingRoundTripper(typicallyTransport) may not be able to re-use a persistent TCPconnection to the server for a subsequent "keep-alive" request.

The request Body, if non-nil, will be closed by the underlyingTransport, even on errors. The Body may be closed asynchronously afterDo returns.

On error, any Response can be ignored. A non-nil Response with anon-nil error only occurs when CheckRedirect fails, and even thenthe returned [Response.Body] is already closed.

GenerallyGet,Post, orPostForm will be used instead of Do.

If the server replies with a redirect, the Client first uses theCheckRedirect function to determine whether the redirect should befollowed. If permitted, a 301, 302, or 303 redirect causessubsequent 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.TheNewRequest function automatically sets GetBody for commonstandard library body types.

Any returned error will be of type*url.Error. The url.Errorvalue's Timeout method will report true if the request timed out.

func (*Client)Get

func (c *Client) Get(urlstring) (resp *Response, errerror)

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

301 (Moved Permanently)302 (Found)303 (See Other)307 (Temporary Redirect)308 (Permanent Redirect)

An error is returned if the [Client.CheckRedirect] function failsor if there was an HTTP protocol error. A non-2xx response doesn'tcause an error. Any returned error will be of type*url.Error. Theurl.Error value's Timeout method will report true if the requesttimed out.

When err is nil, resp always contains a non-nil resp.Body.Caller should close resp.Body when done reading from it.

To make a request with custom headers, useNewRequest andClient.Do.

To make a request with a specified context.Context, useNewRequestWithContextand Client.Do.

func (*Client)Head

func (c *Client) Head(urlstring) (resp *Response, errerror)

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

301 (Moved Permanently)302 (Found)303 (See Other)307 (Temporary Redirect)308 (Permanent Redirect)

To make a request with a specifiedcontext.Context, useNewRequestWithContextandClient.Do.

func (*Client)Post

func (c *Client) Post(url, contentTypestring, bodyio.Reader) (resp *Response, errerror)

Post issues a POST to the specified URL.

Caller should close resp.Body when done reading from it.

If the provided body is anio.Closer, it is closed after therequest.

To set custom headers, useNewRequest andClient.Do.

To make a request with a specified context.Context, useNewRequestWithContextandClient.Do.

See theClient.Do method documentation for details on how redirectsare handled.

func (*Client)PostForm

func (c *Client) PostForm(urlstring, dataurl.Values) (resp *Response, errerror)

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, useNewRequest andClient.Do.

When err is nil, resp always contains a non-nil resp.Body.Caller should close resp.Body when done reading from it.

See theClient.Do method documentation for details on how redirectsare handled.

To make a request with a specified context.Context, useNewRequestWithContextand Client.Do.

typeCloseNotifierdeprecatedadded ingo1.1

type CloseNotifier interface {// CloseNotify returns a channel that receives at most a// single value (true) when the client connection has gone// away.//// CloseNotify may wait to notify until Request.Body has been// fully read.//// After the Handler has returned, there is no guarantee// that the channel receives a value.//// If the protocol is HTTP/1.1 and CloseNotify is called while// processing an idempotent request (such as GET) while// HTTP/1.1 pipelining is in use, the arrival of a subsequent// pipelined request may cause a value to be sent on the// returned channel. In practice HTTP/1.1 pipelining is not// enabled in browsers and not seen often in the wild. If this// is a problem, use HTTP/2 or only use CloseNotify on methods// such as POST.CloseNotify() <-chanbool}

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

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

Deprecated: the CloseNotifier interface predates Go's context package.New code should useRequest.Context instead.

typeConnStateadded ingo1.3

type ConnStateint

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.StateNewConnState =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)

func (ConnState)Stringadded ingo1.3

func (cConnState) String()string

typeCookie

type Cookie struct {NamestringValuestringQuotedbool// indicates whether the Value was originally quotedPathstring// optionalDomainstring// optionalExpirestime.Time// optionalRawExpiresstring// for reading cookies only// MaxAge=0 means no 'Max-Age' attribute specified.// MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'// MaxAge>0 means Max-Age attribute present and given in secondsMaxAgeintSecureboolHttpOnlyboolSameSiteSameSitePartitionedboolRawstringUnparsed    []string// Raw text of unparsed attribute-value pairs}

A Cookie represents an HTTP cookie as sent in the Set-Cookie header of anHTTP response or the Cookie header of an HTTP request.

Seehttps://tools.ietf.org/html/rfc6265 for details.

funcParseCookieadded ingo1.23.0

func ParseCookie(linestring) ([]*Cookie,error)

ParseCookie parses a Cookie header value and returns all the cookieswhich were set in it. Since the same cookie name can appear multiple timesthe returned Values can contain more than one value for a given key.

funcParseSetCookieadded ingo1.23.0

func ParseSetCookie(linestring) (*Cookie,error)

ParseSetCookie parses a Set-Cookie header value and returns a cookie.It returns an error on syntax error.

func (*Cookie)String

func (c *Cookie) String()string

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

func (*Cookie)Validadded ingo1.18

func (c *Cookie) Valid()error

Valid reports whether the cookie is valid.

typeCookieJar

type CookieJar interface {// SetCookies handles the receipt of the cookies in a reply for the// given URL.  It may or may not choose to save the cookies, depending// on the jar's policy and implementation.SetCookies(u *url.URL, cookies []*Cookie)// Cookies returns the cookies to send in a request for the given URL.// It is up to the implementation to honor the standard cookie use// restrictions such as inRFC 6265.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 multiplegoroutines.

The net/http/cookiejar package provides a CookieJar implementation.

typeCrossOriginProtectionadded ingo1.25.0

type CrossOriginProtection struct {// contains filtered or unexported fields}

CrossOriginProtection implements protections againstCross-Site RequestForgery (CSRF) by rejecting non-safe cross-origin browser requests.

Cross-origin requests are currently detected with theSec-Fetch-Siteheader, available in all browsers since 2023, or by comparing the hostname oftheOrigin header with the Host header.

The GET, HEAD, and OPTIONS methods aresafe methods and are always allowed.It's important that applications do not perform any state changing actionsdue to requests with safe methods.

Requests without Sec-Fetch-Site or Origin headers are currently assumed to beeither same-origin or non-browser requests, and are allowed.

The zero value of CrossOriginProtection is valid and has no trusted originsor bypass patterns.

funcNewCrossOriginProtectionadded ingo1.25.0

func NewCrossOriginProtection() *CrossOriginProtection

NewCrossOriginProtection returns a newCrossOriginProtection value.

func (*CrossOriginProtection)AddInsecureBypassPatternadded ingo1.25.0

func (c *CrossOriginProtection) AddInsecureBypassPattern(patternstring)

AddInsecureBypassPattern permits all requests that match the given pattern.

The pattern syntax and precedence rules are the same asServeMux. Onlyrequests that match the pattern directly are permitted. Those that ServeMuxwould redirect to a pattern (e.g. after cleaning the path or adding atrailing slash) are not.

AddInsecureBypassPattern can be called concurrently with other methods orrequest handling, and applies to future requests.

func (*CrossOriginProtection)AddTrustedOriginadded ingo1.25.0

func (c *CrossOriginProtection) AddTrustedOrigin(originstring)error

AddTrustedOrigin allows all requests with anOrigin headerwhich exactly matches the given value.

Origin header values are of the form "scheme://host[:port]".

AddTrustedOrigin can be called concurrently with other methodsor request handling, and applies to future requests.

func (*CrossOriginProtection)Checkadded ingo1.25.0

func (c *CrossOriginProtection) Check(req *Request)error

Check applies cross-origin checks to a request.It returns an error if the request should be rejected.

func (*CrossOriginProtection)Handleradded ingo1.25.0

Handler returns a handler that applies cross-origin checksbefore invoking the handler h.

If a request fails cross-origin checks, the request is rejectedwith a 403 Forbidden status or handled with the handler passedtoCrossOriginProtection.SetDenyHandler.

func (*CrossOriginProtection)SetDenyHandleradded ingo1.25.0

func (c *CrossOriginProtection) SetDenyHandler(hHandler)

SetDenyHandler sets a handler to invoke when a request is rejected.The default error handler responds with a 403 Forbidden status.

SetDenyHandler can be called concurrently with other methodsor request handling, and applies to future requests.

Check does not call the error handler.

typeDir

type Dirstring

A Dir implementsFileSystem using the native file system restricted to aspecific directory tree.

While the [FileSystem.Open] method takes '/'-separated paths, a Dir's stringvalue is a directory path on the native file system, not a URL, so it is separatedbyfilepath.Separator, which isn't necessarily '/'.

Note that Dir could expose sensitive files and directories. Dir will followsymlinks pointing out of the directory tree, which can be especially dangerousif serving from a directory in which users are able to create arbitrary symlinks.Dir will also allow access to files and directories starting with a period,which could expose sensitive directories like .git or sensitive files like.htpasswd. To exclude files with a leading period, remove the files/directoriesfrom the server or create a custom FileSystem implementation.

An empty Dir is treated as ".".

func (Dir)Open

func (dDir) Open(namestring) (File,error)

Open implementsFileSystem usingos.Open, opening files for reading rootedand relative to the directory d.

typeFile

type File interface {io.Closerio.Readerio.SeekerReaddir(countint) ([]fs.FileInfo,error)Stat() (fs.FileInfo,error)}

A File is returned by aFileSystem's Open method and can beserved by theFileServer implementation.

The methods should behave the same as those on an*os.File.

typeFileSystem

type FileSystem interface {Open(namestring) (File,error)}

A FileSystem implements access to a collection of named files.The elements in a file path are separated by slash ('/', U+002F)characters, regardless of host operating system convention.See theFileServer function to convert a FileSystem to aHandler.

This interface predates thefs.FS interface, which can be used instead:theFS adapter function converts an fs.FS to a FileSystem.

funcFSadded ingo1.16

func FS(fsysfs.FS)FileSystem

FS converts fsys to aFileSystem implementation,for use withFileServer andNewFileTransport.The files provided by fsys must implementio.Seeker.

typeFlusher

type Flusher interface {// Flush sends any buffered data to the client.Flush()}

The Flusher interface is implemented by ResponseWriters that allowan HTTP handler to flush buffered data to the client.

The default HTTP/1.x and HTTP/2ResponseWriter implementationssupportFlusher, but ResponseWriter wrappers may not. Handlersshould 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 responsecompletes.

typeHTTP2Configadded ingo1.24.0

type HTTP2Config struct {// MaxConcurrentStreams optionally specifies the number of// concurrent streams that a peer may have open at a time.// If zero, MaxConcurrentStreams defaults to at least 100.MaxConcurrentStreamsint// MaxDecoderHeaderTableSize optionally specifies an upper limit for the// size of the header compression table used for decoding headers sent// by the peer.// A valid value is less than 4MiB.// If zero or invalid, a default value is used.MaxDecoderHeaderTableSizeint// MaxEncoderHeaderTableSize optionally specifies an upper limit for the// header compression table used for sending headers to the peer.// A valid value is less than 4MiB.// If zero or invalid, a default value is used.MaxEncoderHeaderTableSizeint// MaxReadFrameSize optionally specifies the largest frame// this endpoint is willing to read.// A valid value is between 16KiB and 16MiB, inclusive.// If zero or invalid, a default value is used.MaxReadFrameSizeint// MaxReceiveBufferPerConnection is the maximum size of the// flow control window for data received on a connection.// A valid value is at least 64KiB and less than 4MiB.// If invalid, a default value is used.MaxReceiveBufferPerConnectionint// MaxReceiveBufferPerStream is the maximum size of// the flow control window for data received on a stream (request).// A valid value is less than 4MiB.// If zero or invalid, a default value is used.MaxReceiveBufferPerStreamint// SendPingTimeout is the timeout after which a health check using a ping// frame will be carried out if no frame is received on a connection.// If zero, no health check is performed.SendPingTimeouttime.Duration// PingTimeout is the timeout after which a connection will be closed// if a response to a ping is not received.// If zero, a default of 15 seconds is used.PingTimeouttime.Duration// WriteByteTimeout is the timeout after which a connection will be// closed if no data can be written to it. The timeout begins when data is// available to write, and is extended whenever any bytes are written.WriteByteTimeouttime.Duration// PermitProhibitedCipherSuites, if true, permits the use of// cipher suites prohibited by the HTTP/2 spec.PermitProhibitedCipherSuitesbool// CountError, if non-nil, is called on HTTP/2 errors.// It is intended to increment a metric for monitoring.// The errType contains only lowercase letters, digits, and underscores// (a-z, 0-9, _).CountError func(errTypestring)}

HTTP2Config defines HTTP/2 configuration parameters common tobothTransport andServer.

typeHandler

type Handler interface {ServeHTTP(ResponseWriter, *Request)}

A Handler responds to an HTTP request.

[Handler.ServeHTTP] should write reply headers and data to theResponseWriterand then return. Returning signals that the request is finished; itis not valid to use theResponseWriter or read from the[Request.Body] after or concurrently with the completion of theServeHTTP call.

Depending on the HTTP client software, HTTP protocol version, andany intermediaries between the client and the Go server, it may notbe possible to read from the [Request.Body] after writing to theResponseWriter. Cautious handlers should read the [Request.Body]first, and then reply.

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

If ServeHTTP panics, the server (the caller of ServeHTTP) assumesthat 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/2RST_STREAM, depending on the HTTP protocol. To abort a handler sothe client sees an interrupted response but the server doesn't logan error, panic with the valueErrAbortHandler.

funcAllowQuerySemicolonsadded ingo1.17

func AllowQuerySemicolons(hHandler)Handler

AllowQuerySemicolons returns a handler that serves requests by converting anyunescaped semicolons in the URL query to ampersands, and invoking the handler h.

This restores the pre-Go 1.17 behavior of splitting query parameters on bothsemicolons and ampersands. (See golang.org/issue/25192). Note that thisbehavior doesn't match that of many proxies, and the mismatch can lead tosecurity issues.

AllowQuerySemicolons should be invoked beforeRequest.ParseForm is called.

funcFileServer

func FileServer(rootFileSystem)Handler

FileServer returns a handler that serves HTTP requestswith the contents of the file system rooted at root.

As a special case, the returned file server redirects any requestending in "/index.html" to the same path, without the final"index.html".

To use the operating system's file system implementation,usehttp.Dir:

http.Handle("/", http.FileServer(http.Dir("/tmp")))

To use anfs.FS implementation, usehttp.FileServerFS instead.

Example
package mainimport ("log""net/http")func main() {// Simple static webserver:log.Fatal(http.ListenAndServe(":8080", http.FileServer(http.Dir("/usr/share/doc"))))}

Example (DotFileHiding)
package mainimport ("io""io/fs""log""net/http""strings")// containsDotFile reports whether name contains a path element starting with a period.// The name is assumed to be a delimited by forward slashes, as guaranteed// by the http.FileSystem interface.func containsDotFile(name string) bool {parts := strings.Split(name, "/")for _, part := range parts {if strings.HasPrefix(part, ".") {return true}}return false}// dotFileHidingFile is the http.File use in dotFileHidingFileSystem.// It is used to wrap the Readdir method of http.File so that we can// remove files and directories that start with a period from its output.type dotFileHidingFile struct {http.File}// Readdir is a wrapper around the Readdir method of the embedded File// that filters out all files that start with a period in their name.func (f dotFileHidingFile) Readdir(n int) (fis []fs.FileInfo, err error) {files, err := f.File.Readdir(n)for _, file := range files { // Filters out the dot filesif !strings.HasPrefix(file.Name(), ".") {fis = append(fis, file)}}if err == nil && n > 0 && len(fis) == 0 {err = io.EOF}return}// dotFileHidingFileSystem is an http.FileSystem that hides// hidden "dot files" from being served.type dotFileHidingFileSystem struct {http.FileSystem}// Open is a wrapper around the Open method of the embedded FileSystem// that serves a 403 permission error when name has a file or directory// with whose name starts with a period in its path.func (fsys dotFileHidingFileSystem) Open(name string) (http.File, error) {if containsDotFile(name) { // If dot file, return 403 responsereturn nil, fs.ErrPermission}file, err := fsys.FileSystem.Open(name)if err != nil {return nil, err}return dotFileHidingFile{file}, nil}func main() {fsys := dotFileHidingFileSystem{http.Dir(".")}http.Handle("/", http.FileServer(fsys))log.Fatal(http.ListenAndServe(":8080", nil))}

Example (StripPrefix)
package mainimport ("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"))))}

funcFileServerFSadded ingo1.22.0

func FileServerFS(rootfs.FS)Handler

FileServerFS returns a handler that serves HTTP requestswith the contents of the file system fsys.The files provided by fsys must implementio.Seeker.

As a special case, the returned file server redirects any requestending in "/index.html" to the same path, without the final"index.html".

http.Handle("/", http.FileServerFS(fsys))

funcMaxBytesHandleradded ingo1.18

func MaxBytesHandler(hHandler, nint64)Handler

MaxBytesHandler returns aHandler that runs h with itsResponseWriter and [Request.Body] wrapped by a MaxBytesReader.

funcNotFoundHandler

func NotFoundHandler()Handler

NotFoundHandler returns a simple request handlerthat replies to each request with a “404 page not found” reply.

Example
package mainimport ("fmt""log""net/http")func newPeopleHandler() http.Handler {return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {fmt.Fprintln(w, "This is the people handler.")})}func main() {mux := http.NewServeMux()// Create sample handler to returns 404mux.Handle("/resources", http.NotFoundHandler())// Create sample handler that returns 200mux.Handle("/resources/people/", newPeopleHandler())log.Fatal(http.ListenAndServe(":8080", mux))}

funcRedirectHandler

func RedirectHandler(urlstring, codeint)Handler

RedirectHandler returns a request handler that redirectseach request it receives to the given url using the givenstatus code.

The provided code should be in the 3xx range and is usuallyStatusMovedPermanently,StatusFound orStatusSeeOther.

funcStripPrefix

func StripPrefix(prefixstring, hHandler)Handler

StripPrefix returns a handler that serves HTTP requests by removing thegiven prefix from the request URL's Path (and RawPath if set) and invokingthe handler h. StripPrefix handles a request for a path that doesn't beginwith prefix by replying with an HTTP 404 not found error. The prefix mustmatch exactly: if the prefix in the request contains escaped charactersthe reply is also an HTTP 404 not found error.

Example
package mainimport ("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"))))}

funcTimeoutHandler

func TimeoutHandler(hHandler, dttime.Duration, msgstring)Handler

TimeoutHandler returns aHandler that runs h with the given time limit.

The new Handler calls h.ServeHTTP to handle each request, but if acall runs for longer than its time limit, the handler responds witha 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 itsResponseWriter will returnErrHandlerTimeout.

TimeoutHandler supports thePusher interface but does not supporttheHijacker orFlusher interfaces.

typeHandlerFunc

type HandlerFunc func(ResponseWriter, *Request)

The HandlerFunc type is an adapter to allow the use ofordinary functions as HTTP handlers. If f is a functionwith the appropriate signature, HandlerFunc(f) is aHandler that calls f.

func (HandlerFunc)ServeHTTP

func (fHandlerFunc) ServeHTTP(wResponseWriter, r *Request)

ServeHTTP calls f(w, r).

typeHeader

type Header map[string][]string

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

The keys should be in canonical form, as returned byCanonicalHeaderKey.

func (Header)Add

func (hHeader) Add(key, valuestring)

Add adds the key, value pair to the header.It appends to any existing values associated with key.The key is case insensitive; it is canonicalized byCanonicalHeaderKey.

func (Header)Cloneadded ingo1.13

func (hHeader) Clone()Header

Clone returns a copy of h or nil if h is nil.

func (Header)Del

func (hHeader) Del(keystring)

Del deletes the values associated with key.The key is case insensitive; it is canonicalized byCanonicalHeaderKey.

func (Header)Get

func (hHeader) Get(keystring)string

Get gets the first value associated with the given key. Ifthere are no values associated with the key, Get returns "".It is case insensitive;textproto.CanonicalMIMEHeaderKey isused to canonicalize the provided key. Get assumes that allkeys are stored in canonical form. To use non-canonical keys,access the map directly.

func (Header)Set

func (hHeader) Set(key, valuestring)

Set sets the header entries associated with key to thesingle element value. It replaces any existing valuesassociated with key. The key is case insensitive; it iscanonicalized bytextproto.CanonicalMIMEHeaderKey.To use non-canonical keys, assign to the map directly.

func (Header)Valuesadded ingo1.14

func (hHeader) Values(keystring) []string

Values returns all values associated with the given key.It is case insensitive;textproto.CanonicalMIMEHeaderKey isused to canonicalize the provided key. To use non-canonicalkeys, access the map directly.The returned slice is not a copy.

func (Header)Write

func (hHeader) Write(wio.Writer)error

Write writes a header in wire format.

func (Header)WriteSubset

func (hHeader) WriteSubset(wio.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.Keys are not canonicalized before checking the exclude map.

typeHijacker

type Hijacker interface {// Hijack lets the caller take over the connection.// After a call to Hijack the HTTP server library// will not do anything else with the connection.//// It becomes the caller's responsibility to manage// and close the connection.//// The returned net.Conn may have read or write deadlines// already set, depending on the configuration of the// Server. It is the caller's responsibility to set// or clear those deadlines as needed.//// The returned bufio.Reader may contain unprocessed buffered// data from the client.//// After a call to Hijack, the original Request.Body must not// be used. The original Request's Context remains valid and// is not canceled until the Request's ServeHTTP method// returns.Hijack() (net.Conn, *bufio.ReadWriter,error)}

The Hijacker interface is implemented by ResponseWriters that allowan HTTP handler to take over the connection.

The defaultResponseWriter for HTTP/1.x connections supportsHijacker, but HTTP/2 connections intentionally do not.ResponseWriter wrappers may also not support Hijacker. Handlersshould always test for this ability at runtime.

Example
package mainimport ("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()})}

typeMaxBytesErroradded ingo1.19

type MaxBytesError struct {Limitint64}

MaxBytesError is returned byMaxBytesReader when its read limit is exceeded.

func (*MaxBytesError)Erroradded ingo1.19

func (e *MaxBytesError) Error()string

typeProtocolErrordeprecated

type ProtocolError struct {ErrorStringstring}

ProtocolError represents an HTTP protocol error.

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

func (*ProtocolError)Error

func (pe *ProtocolError) Error()string

func (*ProtocolError)Isadded ingo1.21.0

func (pe *ProtocolError) Is(errerror)bool

Is lets http.ErrNotSupported match errors.ErrUnsupported.

typeProtocolsadded ingo1.24.0

type Protocols struct {// contains filtered or unexported fields}

Protocols is a set of HTTP protocols.The zero value is an empty set of protocols.

The supported protocols are:

  • HTTP1 is the HTTP/1.0 and HTTP/1.1 protocols.HTTP1 is supported on both unsecured TCP and secured TLS connections.

  • HTTP2 is the HTTP/2 protcol over a TLS connection.

  • UnencryptedHTTP2 is the HTTP/2 protocol over an unsecured TCP connection.

Example (Http1)
package mainimport ("log""net/http")func main() {srv := http.Server{Addr: ":8443",}// Serve only HTTP/1.srv.Protocols = new(http.Protocols)srv.Protocols.SetHTTP1(true)log.Fatal(srv.ListenAndServeTLS("cert.pem", "key.pem"))}

Example (Http1or2)
package mainimport ("log""net/http")func main() {t := http.DefaultTransport.(*http.Transport).Clone()// Use either HTTP/1 and HTTP/2.t.Protocols = new(http.Protocols)t.Protocols.SetHTTP1(true)t.Protocols.SetHTTP2(true)cli := &http.Client{Transport: t}res, err := cli.Get("http://www.google.com/robots.txt")if err != nil {log.Fatal(err)}res.Body.Close()}

func (Protocols)HTTP1added ingo1.24.0

func (pProtocols) HTTP1()bool

HTTP1 reports whether p includes HTTP/1.

func (Protocols)HTTP2added ingo1.24.0

func (pProtocols) HTTP2()bool

HTTP2 reports whether p includes HTTP/2.

func (*Protocols)SetHTTP1added ingo1.24.0

func (p *Protocols) SetHTTP1(okbool)

SetHTTP1 adds or removes HTTP/1 from p.

func (*Protocols)SetHTTP2added ingo1.24.0

func (p *Protocols) SetHTTP2(okbool)

SetHTTP2 adds or removes HTTP/2 from p.

func (*Protocols)SetUnencryptedHTTP2added ingo1.24.0

func (p *Protocols) SetUnencryptedHTTP2(okbool)

SetUnencryptedHTTP2 adds or removes unencrypted HTTP/2 from p.

func (Protocols)Stringadded ingo1.24.0

func (pProtocols) String()string

func (Protocols)UnencryptedHTTP2added ingo1.24.0

func (pProtocols) UnencryptedHTTP2()bool

UnencryptedHTTP2 reports whether p includes unencrypted HTTP/2.

typePushOptionsadded ingo1.8

type PushOptions struct {// Method specifies the HTTP method for the promised request.// If set, it must be "GET" or "HEAD". Empty means "GET".Methodstring// Header specifies additional promised request headers. This cannot// include HTTP/2 pseudo header fields like ":path" and ":scheme",// which will be added automatically.HeaderHeader}

PushOptions describes options for [Pusher.Push].

typePusheradded ingo1.8

type Pusher interface {// Push initiates an HTTP/2 server push. This constructs a synthetic// request using the given target and options, serializes that request// into a PUSH_PROMISE frame, then dispatches that request using the// server's request handler. If opts is nil, default options are used.//// The target must either be an absolute path (like "/path") or an absolute// URL that contains a valid host and the same scheme as the parent request.// If the target is a path, it will inherit the scheme and host of the// parent request.//// The HTTP/2 spec disallows recursive pushes and cross-authority pushes.// Push may or may not detect these invalid pushes; however, invalid// pushes will be detected and canceled by conforming clients.//// Handlers that wish to push URL X should call Push before sending any// data that may trigger a request for URL X. This avoids a race where the// client issues requests for X before receiving the PUSH_PROMISE for X.//// Push will run in a separate goroutine making the order of arrival// non-deterministic. Any required synchronization needs to be implemented// by the caller.//// Push returns ErrNotSupported if the client has disabled push or if push// is not supported on the underlying connection.Push(targetstring, opts *PushOptions)error}

Pusher is the interface implemented by ResponseWriters that supportHTTP/2 server push. For more background, seehttps://tools.ietf.org/html/rfc7540#section-8.2.

typeRequest

type Request struct {// Method specifies the HTTP method (GET, POST, PUT, etc.).// For client requests, an empty string means GET.Methodstring// URL specifies either the URI being requested (for server// requests) or the URL to access (for client requests).//// For server requests, the URL is parsed from the URI// supplied on the Request-Line as stored in RequestURI.  For// most requests, fields other than Path and RawQuery will be// empty. (SeeRFC 7230, Section 5.3)//// For client requests, the URL's Host specifies the server to// connect to, while the Request's Host field optionally// specifies the Host header value to send in the HTTP// request.URL *url.URL// The protocol version for incoming server requests.//// For client requests, these fields are ignored. The HTTP// client code always uses either HTTP/1.1 or HTTP/2.// See the docs on Transport for details.Protostring// "HTTP/1.0"ProtoMajorint// 1ProtoMinorint// 0// Header contains the request header fields either received// by the server or to be sent by the client.//// If a server received a request with header lines,////Host: example.com//accept-encoding: gzip, deflate//Accept-Language: en-us//fOO: Bar//foo: two//// then////Header = map[string][]string{//"Accept-Encoding": {"gzip, deflate"},//"Accept-Language": {"en-us"},//"Foo": {"Bar", "two"},//}//// For incoming requests, the Host header is promoted to the// Request.Host field and removed from the Header map.//// HTTP defines that header names are case-insensitive. The// request parser implements this by using CanonicalHeaderKey,// making the first character and any characters following a// hyphen uppercase and the rest lowercase.//// For client requests, certain headers such as Content-Length// and Connection are automatically written when needed and// values in Header may be ignored. See the documentation// for the Request.Write method.HeaderHeader// Body is the request's body.//// For client requests, a nil body means the request has no// body, such as a GET request. The HTTP Client's Transport// is responsible for calling the Close method.//// For server requests, the Request Body is always non-nil// but will return EOF immediately when no body is present.// The Server will close the request body. The ServeHTTP// Handler does not need to.//// Body must allow Read to be called concurrently with Close.// In particular, calling Close should unblock a Read waiting// for input.Bodyio.ReadCloser// GetBody defines an optional func to return a new copy of// Body. It is used for client requests when a redirect requires// reading the body more than once. Use of GetBody still// requires setting Body.//// For server requests, it is unused.GetBody func() (io.ReadCloser,error)// ContentLength records the length of the associated content.// The value -1 indicates that the length is unknown.// Values >= 0 indicate that the given number of bytes may// be read from Body.//// For client requests, a value of 0 with a non-nil Body is// also treated as unknown.ContentLengthint64// TransferEncoding lists the transfer encodings from outermost to// innermost. An empty list denotes the "identity" encoding.// TransferEncoding can usually be ignored; chunked encoding is// automatically added and removed as necessary when sending and// receiving requests.TransferEncoding []string// Close indicates whether to close the connection after// replying to this request (for servers) or after sending this// request and reading its response (for clients).//// For server requests, the HTTP server handles this automatically// and this field is not needed by Handlers.//// For client requests, setting this field prevents re-use of// TCP connections between requests to the same hosts, as if// Transport.DisableKeepAlives were set.Closebool// For server requests, Host specifies the host on which the// URL is sought. For HTTP/1 (perRFC 7230, section 5.4), this// is either the value of the "Host" header or the host name// given in the URL itself. For HTTP/2, it is the value of the// ":authority" pseudo-header field.// It may be of the form "host:port". For international domain// names, Host may be in Punycode or Unicode form. Use// golang.org/x/net/idna to convert it to either format if// needed.// To prevent DNS rebinding attacks, server Handlers should// validate that the Host header has a value for which the// Handler considers itself authoritative. The included// ServeMux supports patterns registered to particular host// names and thus protects its registered Handlers.//// For client requests, Host optionally overrides the Host// header to send. If empty, the Request.Write method uses// the value of URL.Host. Host may contain an international// domain name.Hoststring// Form contains the parsed form data, including both the URL// field's query parameters and the PATCH, POST, or PUT form data.// This field is only available after ParseForm is called.// The HTTP client ignores Form and uses Body instead.Formurl.Values// PostForm contains the parsed form data from PATCH, POST// or PUT body parameters.//// This field is only available after ParseForm is called.// The HTTP client ignores PostForm and uses Body instead.PostFormurl.Values// MultipartForm is the parsed multipart form, including file uploads.// This field is only available after ParseMultipartForm is called.// The HTTP client ignores MultipartForm and uses Body instead.MultipartForm *multipart.Form// Trailer specifies additional headers that are sent after the request// body.//// For server requests, the Trailer map initially contains only the// trailer keys, with nil values. (The client declares which trailers it// will later send.)  While the handler is reading from Body, it must// not reference Trailer. After reading from Body returns EOF, Trailer// can be read again and will contain non-nil values, if they were sent// by the client.//// For client requests, Trailer must be initialized to a map containing// the trailer keys to later send. The values may be nil or their final// values. The ContentLength must be 0 or -1, to send a chunked request.// After the HTTP request is sent the map values can be updated while// the request body is read. Once the body returns EOF, the caller must// not mutate Trailer.//// Few HTTP clients, servers, or proxies support HTTP trailers.TrailerHeader// RemoteAddr allows HTTP servers and other software to record// the network address that sent the request, usually for// logging. This field is not filled in by ReadRequest and// has no defined format. The HTTP server in this package// sets RemoteAddr to an "IP:port" address before invoking a// handler.// This field is ignored by the HTTP client.RemoteAddrstring// RequestURI is the unmodified request-target of the// Request-Line (RFC 7230, Section 3.1.1) as sent by the client// to a server. Usually the URL field should be used instead.// It is an error to set this field in an HTTP client request.RequestURIstring// TLS allows HTTP servers and other software to record// information about the TLS connection on which the request// was received. This field is not filled in by ReadRequest.// The HTTP server in this package sets the field for// TLS-enabled connections before invoking a handler;// otherwise it leaves the field nil.// This field is ignored by the HTTP client.TLS *tls.ConnectionState// Cancel is an optional channel whose closure indicates that the client// request should be regarded as canceled. Not all implementations of// RoundTripper may support Cancel.//// For server requests, this field is not applicable.//// Deprecated: Set the Request's context with NewRequestWithContext// instead. If a Request's Cancel field and context are both// set, it is undefined whether Cancel is respected.Cancel <-chan struct{}// Response is the redirect response which caused this request// to be created. This field is only populated during client// redirects.Response *Response// Pattern is the [ServeMux] pattern that matched the request.// It is empty if the request was not matched against a pattern.Patternstring// contains filtered or unexported fields}

A Request represents an HTTP request received by a serveror to be sent by a client.

The field semantics differ slightly between client and serverusage. In addition to the notes on the fields below, see thedocumentation forRequest.Write andRoundTripper.

funcNewRequest

func NewRequest(method, urlstring, bodyio.Reader) (*Request,error)

NewRequest wrapsNewRequestWithContext usingcontext.Background.

funcNewRequestWithContextadded ingo1.13

func NewRequestWithContext(ctxcontext.Context, method, urlstring, bodyio.Reader) (*Request,error)

NewRequestWithContext returns a newRequest given a method, URL, andoptional body.

If the provided body is also anio.Closer, the returned[Request.Body] is set to body and will be closed (possiblyasynchronously) by the Client methods Do, Post, and PostForm,andTransport.RoundTrip.

NewRequestWithContext returns a Request suitable for use withClient.Do orTransport.RoundTrip. To create a request for use withtesting a Server Handler, either use thenet/http/httptest.NewRequest function,useReadRequest, or manually update the Request fields.For an outgoing client request, the contextcontrols the entire lifetime of a request and its response:obtaining a connection, sending the request, and reading theresponse headers and body. See theRequest type's documentation forthe 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 itsexact value (instead of -1), GetBody is populated (so 307 and 308redirects can replay the body), and Body is set toNoBody if theContentLength is 0.

funcReadRequest

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

ReadRequest reads and parses an incoming request from b.

ReadRequest is a low-level function and should only be used forspecialized applications; most code should use theServer to readrequests and handle them via theHandler interface. ReadRequestonly supports HTTP/1.x requests. For HTTP/2, use golang.org/x/net/http2.

func (*Request)AddCookie

func (r *Request) AddCookie(c *Cookie)

AddCookie adds a cookie to the request. PerRFC 6265 section 5.4,AddCookie does not attach more than oneCookie header field. Thatmeans all cookies, if any, are written into the same line,separated by semicolon.AddCookie only sanitizes c's name and value, and does not sanitizea Cookie header already present in the request.

func (*Request)BasicAuthadded ingo1.4

func (r *Request) BasicAuth() (username, passwordstring, okbool)

BasicAuth returns the username and password provided in the request'sAuthorization header, if the request uses HTTP Basic Authentication.SeeRFC 2617, Section 2.

func (*Request)Cloneadded ingo1.13

func (r *Request) Clone(ctxcontext.Context) *Request

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

Clone only makes a shallow copy of the Body field.

For an outgoing client request, the context controls the entirelifetime of a request and its response: obtaining a connection,sending the request, and reading the response headers and body.

func (*Request)Contextadded ingo1.7

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

Context returns the request's context. To change the context, useRequest.Clone orRequest.WithContext.

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

For outgoing client requests, the context controls cancellation.

For incoming server requests, the context is canceled when theclient's connection closes, the request is canceled (with HTTP/2),or when the ServeHTTP method returns.

func (*Request)Cookie

func (r *Request) Cookie(namestring) (*Cookie,error)

Cookie returns the named cookie provided in the request orErrNoCookie if not found.If multiple cookies match the given name, only one cookie willbe returned.

func (*Request)Cookies

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

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

func (*Request)CookiesNamedadded ingo1.23.0

func (r *Request) CookiesNamed(namestring) []*Cookie

CookiesNamed parses and returns the named HTTP cookies sent with the requestor an empty slice if none matched.

func (*Request)FormFile

FormFile returns the first file for the provided form key.FormFile callsRequest.ParseMultipartForm andRequest.ParseForm if necessary.

func (*Request)FormValue

func (r *Request) FormValue(keystring)string

FormValue returns the first value for the named component of the query.The precedence order:

  1. application/x-www-form-urlencoded form body (POST, PUT, PATCH only)
  2. query parameters (always)
  3. multipart/form-data form body (always)

FormValue callsRequest.ParseMultipartForm andRequest.ParseFormif 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 andthen inspect [Request.Form] directly.

func (*Request)MultipartReader

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

MultipartReader returns a MIME multipart reader if this is amultipart/form-data or a multipart/mixed POST request, else returns nil and an error.Use this function instead ofRequest.ParseMultipartForm toprocess the request body as a stream.

func (*Request)ParseForm

func (r *Request) ParseForm()error

ParseForm populates r.Form and r.PostForm.

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

For POST, PUT, and PATCH requests, it also reads the request body, parses itas a form and puts the results into both r.PostForm and r.Form. Request bodyparameters take precedence over URL query string values in r.Form.

If the request Body's size has not already been limited byMaxBytesReader,the size is capped at 10MB.

For other HTTP methods, or when the Content-Type is notapplication/x-www-form-urlencoded, the request Body is not read, andr.PostForm is initialized to a non-nil, empty value.

Request.ParseMultipartForm calls ParseForm automatically.ParseForm is idempotent.

func (*Request)ParseMultipartForm

func (r *Request) ParseMultipartForm(maxMemoryint64)error

ParseMultipartForm parses a request body as multipart/form-data.The whole request body is parsed and up to a total of maxMemory bytes ofits file parts are stored in memory, with the remainder stored ondisk in temporary files.ParseMultipartForm callsRequest.ParseForm if necessary.If ParseForm returns an error, ParseMultipartForm returns it but alsocontinues parsing the request body.After one call to ParseMultipartForm, subsequent calls have no effect.

func (*Request)PathValueadded ingo1.22.0

func (r *Request) PathValue(namestring)string

PathValue returns the value for the named path wildcard in theServeMux patternthat matched the request.It returns the empty string if the request was not matched against a patternor there is no such wildcard in the pattern.

func (*Request)PostFormValueadded ingo1.1

func (r *Request) PostFormValue(keystring)string

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

func (*Request)ProtoAtLeast

func (r *Request) ProtoAtLeast(major, minorint)bool

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

func (*Request)Referer

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 theearliest days of HTTP. This value can also be fetched from theHeader map as Header["Referer"]; the benefit of making it availableas a method is that the compiler can diagnose programs that use thealternate (correct English) spelling req.Referrer() but cannotdiagnose programs that use Header["Referrer"].

func (*Request)SetBasicAuth

func (r *Request) SetBasicAuth(username, passwordstring)

SetBasicAuth sets the request's Authorization header to use HTTPBasic Authentication with the provided username and password.

With HTTP Basic Authentication the provided username and passwordare not encrypted. It should generally only be used in an HTTPSrequest.

The username may not contain a colon. Some protocols may imposeadditional requirements on pre-escaping the username andpassword. For instance, when used with OAuth2, both arguments mustbe URL encoded first withurl.QueryEscape.

func (*Request)SetPathValueadded ingo1.22.0

func (r *Request) SetPathValue(name, valuestring)

SetPathValue sets name to value, so that subsequent calls to r.PathValue(name)return value.

func (*Request)UserAgent

func (r *Request) UserAgent()string

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

func (*Request)WithContextadded ingo1.7

func (r *Request) WithContext(ctxcontext.Context) *Request

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

For outgoing client request, the context controls the entirelifetime of a request and its response: obtaining a connection,sending the request, and reading the response headers and body.

To create a new request with a context, useNewRequestWithContext.To make a deep copy of a request with a new context, useRequest.Clone.

func (*Request)Write

func (r *Request) Write(wio.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:

HostURLMethod (defaults to "GET")HeaderContentLengthTransferEncodingBody

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

func (*Request)WriteProxy

func (r *Request) WriteProxy(wio.Writer)error

WriteProxy is likeRequest.Write but writes the request in the formexpected by an HTTP proxy. In particular,Request.WriteProxy writes theinitial Request-URI line of the request with an absolute URI, persection 5.3 ofRFC 7230, including the scheme and host.In either case, WriteProxy also writes a Host header, usingeither r.Host or r.URL.Host.

typeResponse

type Response struct {Statusstring// e.g. "200 OK"StatusCodeint// e.g. 200Protostring// e.g. "HTTP/1.0"ProtoMajorint// e.g. 1ProtoMinorint// e.g. 0// Header maps header keys to values. If the response had multiple// headers with the same key, they may be concatenated, with comma// delimiters.  (RFC 7230, section 3.2.2 requires that multiple headers// be semantically equivalent to a comma-delimited sequence.) When// Header values are duplicated by other fields in this struct (e.g.,// ContentLength, TransferEncoding, Trailer), the field values are// authoritative.//// Keys in the map are canonicalized (see CanonicalHeaderKey).HeaderHeader// Body represents the response body.//// The response body is streamed on demand as the Body field// is read. If the network connection fails or the server// terminates the response, Body.Read calls return an error.//// The http Client and Transport guarantee that Body is always// non-nil, even on responses without a body or responses with// a zero-length body. It is the caller's responsibility to// close Body. The default HTTP client's Transport may not// reuse HTTP/1.x "keep-alive" TCP connections if the Body is// not read to completion and closed.//// The Body is automatically dechunked if the server replied// with a "chunked" Transfer-Encoding.//// As of Go 1.12, the Body will also implement io.Writer// on a successful "101 Switching Protocols" response,// as used by WebSockets and HTTP/2's "h2c" mode.Bodyio.ReadCloser// ContentLength records the length of the associated content. The// value -1 indicates that the length is unknown. Unless Request.Method// is "HEAD", values >= 0 indicate that the given number of bytes may// be read from Body.ContentLengthint64// Contains transfer encodings from outer-most to inner-most. Value is// nil, means that "identity" encoding is used.TransferEncoding []string// Close records whether the header directed that the connection be// closed after reading Body. The value is advice for clients: neither// ReadResponse nor Response.Write ever closes a connection.Closebool// Uncompressed reports whether the response was sent compressed but// was decompressed by the http package. When true, reading from// Body yields the uncompressed content instead of the compressed// content actually set from the server, ContentLength is set to -1,// and the "Content-Length" and "Content-Encoding" fields are deleted// from the responseHeader. To get the original response from// the server, set Transport.DisableCompression to true.Uncompressedbool// Trailer maps trailer keys to values in the same// format as Header.//// The Trailer initially contains only nil values, one for// each key specified in the server's "Trailer" header// value. Those values are not added to Header.//// Trailer must not be accessed concurrently with Read calls// on the Body.//// After Body.Read has returned io.EOF, Trailer will contain// any trailer values sent by the server.TrailerHeader// Request is the request that was sent to obtain this Response.// Request's Body is nil (having already been consumed).// This is only populated for Client requests.Request *Request// TLS contains information about the TLS connection on which the// response was received. It is nil for unencrypted responses.// The pointer is shared between responses and should not be// modified.TLS *tls.ConnectionState}

Response represents the response from an HTTP request.

TheClient andTransport return Responses from servers oncethe response headers have been received. The response bodyis streamed on demand as the Body field is read.

funcGet

func Get(urlstring) (resp *Response, errerror)

Get issues a GET to the specified URL. If the response is one ofthe following redirect codes, Get follows the redirect, up to amaximum of 10 redirects:

301 (Moved Permanently)302 (Found)303 (See Other)307 (Temporary Redirect)308 (Permanent Redirect)

An error is returned if there were too many redirects or if therewas an HTTP protocol error. A non-2xx response doesn't cause anerror. Any returned error will be of type*url.Error. The url.Errorvalue's Timeout method will report true if the request timed out.

When err is nil, resp always contains a non-nil resp.Body.Caller should close resp.Body when done reading from it.

Get is a wrapper around DefaultClient.Get.

To make a request with custom headers, useNewRequest andDefaultClient.Do.

To make a request with a specified context.Context, useNewRequestWithContextand DefaultClient.Do.

Example
package mainimport ("fmt""io""log""net/http")func main() {res, err := http.Get("http://www.google.com/robots.txt")if err != nil {log.Fatal(err)}body, err := io.ReadAll(res.Body)res.Body.Close()if res.StatusCode > 299 {log.Fatalf("Response failed with status code: %d and\nbody: %s\n", res.StatusCode, body)}if err != nil {log.Fatal(err)}fmt.Printf("%s", body)}

funcHead

func Head(urlstring) (resp *Response, errerror)

Head issues a HEAD to the specified URL. If the response is one ofthe following redirect codes, Head follows the redirect, up to amaximum of 10 redirects:

301 (Moved Permanently)302 (Found)303 (See Other)307 (Temporary Redirect)308 (Permanent Redirect)

Head is a wrapper around DefaultClient.Head.

To make a request with a specifiedcontext.Context, useNewRequestWithContextand DefaultClient.Do.

funcPost

func Post(url, contentTypestring, bodyio.Reader) (resp *Response, errerror)

Post issues a POST to the specified URL.

Caller should close resp.Body when done reading from it.

If the provided body is anio.Closer, it is closed after therequest.

Post is a wrapper around DefaultClient.Post.

To set custom headers, useNewRequest and DefaultClient.Do.

See theClient.Do method documentation for details on how redirectsare handled.

To make a request with a specified context.Context, useNewRequestWithContextand DefaultClient.Do.

funcPostForm

func PostForm(urlstring, dataurl.Values) (resp *Response, errerror)

PostForm issues a POST to the specified URL, with data's keys andvalues URL-encoded as the request body.

The Content-Type header is set to application/x-www-form-urlencoded.To set other headers, useNewRequest 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 theClient.Do method documentation for details on how redirectsare handled.

To make a request with a specifiedcontext.Context, useNewRequestWithContextand DefaultClient.Do.

funcReadResponse

func ReadResponse(r *bufio.Reader, req *Request) (*Response,error)

ReadResponse reads and returns an HTTP response from r.The req parameter optionally specifies theRequest that correspondsto thisResponse. 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/valuepairs included in the response trailer.

func (*Response)Cookies

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

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

func (*Response)Location

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[Response.Request].ErrNoLocation is returned if noLocation header is present.

func (*Response)ProtoAtLeast

func (r *Response) ProtoAtLeast(major, minorint)bool

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

func (*Response)Write

func (r *Response) Write(wio.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:

StatusCodeProtoMajorProtoMinorRequest.MethodTransferEncodingTrailerBodyContentLengthHeader, values for non-canonical keys will have unpredictable behavior

The Response Body is closed after it is sent.

typeResponseControlleradded ingo1.20

type ResponseController struct {// contains filtered or unexported fields}

A ResponseController is used by an HTTP handler to control the response.

A ResponseController may not be used after the [Handler.ServeHTTP] method has returned.

funcNewResponseControlleradded ingo1.20

func NewResponseController(rwResponseWriter) *ResponseController

NewResponseController creates aResponseController for a request.

The ResponseWriter should be the original value passed to the [Handler.ServeHTTP] method,or have an Unwrap method returning the original ResponseWriter.

If the ResponseWriter implements any of the following methods, the ResponseControllerwill call them as appropriate:

Flush()FlushError() error // alternative Flush returning an errorHijack() (net.Conn, *bufio.ReadWriter, error)SetReadDeadline(deadline time.Time) errorSetWriteDeadline(deadline time.Time) errorEnableFullDuplex() error

If the ResponseWriter does not support a method, ResponseController returnsan error matchingErrNotSupported.

func (*ResponseController)EnableFullDuplexadded ingo1.21.0

func (c *ResponseController) EnableFullDuplex()error

EnableFullDuplex indicates that the request handler will interleave reads from [Request.Body]with writes to theResponseWriter.

For HTTP/1 requests, the Go HTTP server by default consumes any unread portion ofthe request body before beginning to write the response, preventing handlers fromconcurrently reading from the request and writing the response.Calling EnableFullDuplex disables this behavior and permits handlers to continue to readfrom the request while concurrently writing the response.

For HTTP/2 requests, the Go HTTP server always permits concurrent reads and responses.

func (*ResponseController)Flushadded ingo1.20

func (c *ResponseController) Flush()error

Flush flushes buffered data to the client.

func (*ResponseController)Hijackadded ingo1.20

Hijack lets the caller take over the connection.See theHijacker interface for details.

func (*ResponseController)SetReadDeadlineadded ingo1.20

func (c *ResponseController) SetReadDeadline(deadlinetime.Time)error

SetReadDeadline sets the deadline for reading the entire request, including the body.Reads from the request body after the deadline has been exceeded will return an error.A zero value means no deadline.

Setting the read deadline after it has been exceeded will not extend it.

func (*ResponseController)SetWriteDeadlineadded ingo1.20

func (c *ResponseController) SetWriteDeadline(deadlinetime.Time)error

SetWriteDeadline sets the deadline for writing the response.Writes to the response body after the deadline has been exceeded will not block,but may succeed if the data has been buffered.A zero value means no deadline.

Setting the write deadline after it has been exceeded will not extend it.

typeResponseWriter

type ResponseWriter interface {// Header returns the header map that will be sent by// [ResponseWriter.WriteHeader]. The [Header] map also is the mechanism with which// [Handler] implementations can set HTTP trailers.//// Changing the header map after a call to [ResponseWriter.WriteHeader] (or// [ResponseWriter.Write]) has no effect unless the HTTP status code was of the// 1xx class or the modified headers are trailers.//// There are two ways to set Trailers. The preferred way is to// predeclare in the headers which trailers you will later// send by setting the "Trailer" header to the names of the// trailer keys which will come later. In this case, those// keys of the Header map are treated as if they were// trailers. See the example. The second way, for trailer// keys not known to the [Handler] until after the first [ResponseWriter.Write],// is to prefix the [Header] map keys with the [TrailerPrefix]// constant value.//// To suppress automatic response headers (such as "Date"), set// their value to nil.Header()Header// Write writes the data to the connection as part of an HTTP reply.//// If [ResponseWriter.WriteHeader] has not yet been called, Write calls// WriteHeader(http.StatusOK) before writing the data. If the Header// does not contain a Content-Type line, Write adds a Content-Type set// to the result of passing the initial 512 bytes of written data to// [DetectContentType]. Additionally, if the total size of all written// data is under a few KB and there are no Flush calls, the// Content-Length header is added automatically.//// Depending on the HTTP protocol version and the client, calling// Write or WriteHeader may prevent future reads on the// Request.Body. For HTTP/1.x requests, handlers should read any// needed request body data before writing the response. Once the// headers have been flushed (due to either an explicit Flusher.Flush// call or writing enough data to trigger a flush), the request body// may be unavailable. For HTTP/2 requests, the Go HTTP server permits// handlers to continue to read the request body while concurrently// writing the response. However, such behavior may not be supported// by all HTTP/2 clients. Handlers should read before writing if// possible to maximize compatibility.Write([]byte) (int,error)// WriteHeader sends an HTTP response header with the provided// status code.//// If WriteHeader is not called explicitly, the first call to Write// will trigger an implicit WriteHeader(http.StatusOK).// Thus explicit calls to WriteHeader are mainly used to// send error codes or 1xx informational responses.//// The provided code must be a valid HTTP 1xx-5xx status code.// Any number of 1xx headers may be written, followed by at most// one 2xx-5xx header. 1xx headers are sent immediately, but 2xx-5xx// headers may be buffered. Use the Flusher interface to send// buffered data. The header map is cleared when 2xx-5xx headers are// sent, but not with 1xx headers.//// The server will automatically send a 100 (Continue) header// on the first read from the request body if the request has// an "Expect: 100-continue" header.WriteHeader(statusCodeint)}

A ResponseWriter interface is used by an HTTP handler toconstruct an HTTP response.

A ResponseWriter may not be used after [Handler.ServeHTTP] has returned.

Example (Trailers)

HTTP Trailers are a set of key/value pairs like headers that comeafter the HTTP response, instead of before.

package mainimport ("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 headerw.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.})}

typeRoundTripper

type RoundTripper interface {// RoundTrip executes a single HTTP transaction, returning// a Response for the provided Request.//// RoundTrip should not attempt to interpret the response. In// particular, RoundTrip must return err == nil if it obtained// a response, regardless of the response's HTTP status code.// A non-nil err should be reserved for failure to obtain a// response. Similarly, RoundTrip should not attempt to// handle higher-level protocol details such as redirects,// authentication, or cookies.//// RoundTrip should not modify the request, except for// consuming and closing the Request's Body. RoundTrip may// read fields of the request in a separate goroutine. Callers// should not mutate or reuse the request until the Response's// Body has been closed.//// RoundTrip must always close the body, including on errors,// but depending on the implementation may do so in a separate// goroutine even after RoundTrip returns. This means that// callers wanting to reuse the body for subsequent requests// must arrange to wait for the Close call before doing so.//// The Request's URL and Header fields must be initialized.RoundTrip(*Request) (*Response,error)}

RoundTripper is an interface representing the ability to execute asingle HTTP transaction, obtaining theResponse for a givenRequest.

A RoundTripper must be safe for concurrent use by multiplegoroutines.

var DefaultTransportRoundTripper = &Transport{Proxy:ProxyFromEnvironment,DialContext: defaultTransportDialContext(&net.Dialer{Timeout:   30 *time.Second,KeepAlive: 30 *time.Second,}),ForceAttemptHTTP2:true,MaxIdleConns:          100,IdleConnTimeout:       90 *time.Second,TLSHandshakeTimeout:   10 *time.Second,ExpectContinueTimeout: 1 *time.Second,}

DefaultTransport is the default implementation ofTransport and isused byDefaultClient. It establishes network connections as neededand caches them for reuse by subsequent calls. It uses HTTP proxiesas directed by the environment variables HTTP_PROXY, HTTPS_PROXYand NO_PROXY (or the lowercase versions thereof).

funcNewFileTransport

func NewFileTransport(fsFileSystem)RoundTripper

NewFileTransport returns a newRoundTripper, serving the providedFileSystem. The returned RoundTripper ignores the URL host in itsincoming requests, as well as most other properties of therequest.

The typical use case for NewFileTransport is to register the "file"protocol with aTransport, as in:

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

funcNewFileTransportFSadded ingo1.22.0

func NewFileTransportFS(fsysfs.FS)RoundTripper

NewFileTransportFS returns a newRoundTripper, serving the providedfile system fsys. The returned RoundTripper ignores the URL host in itsincoming requests, as well as most other properties of therequest. The files provided by fsys must implementio.Seeker.

The typical use case for NewFileTransportFS is to register the "file"protocol with aTransport, as in:

fsys := os.DirFS("/")t := &http.Transport{}t.RegisterProtocol("file", http.NewFileTransportFS(fsys))c := &http.Client{Transport: t}res, err := c.Get("file:///etc/passwd")...

typeSameSiteadded ingo1.11

type SameSiteint

SameSite allows a server to define a cookie attribute making it impossible forthe browser to send this cookie along with cross-site requests. The maingoal is to mitigate the risk of cross-origin information leakage, and providesome protection against cross-site request forgery attacks.

Seehttps://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00 for details.

const (SameSiteDefaultModeSameSite =iota + 1SameSiteLaxModeSameSiteStrictModeSameSiteNoneMode)

typeServeMux

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 registeredpatterns and calls the handler for the pattern thatmost closely matches the URL.

Patterns

Patterns can match the method, host and path of a request.Some examples:

  • "/index.html" matches the path "/index.html" for any host and method.
  • "GET /static/" matches a GET request whose path begins with "/static/".
  • "example.com/" matches any request to the host "example.com".
  • "example.com/{$}" matches requests with host "example.com" and path "/".
  • "/b/{bucket}/o/{objectname...}" matches paths whose first segment is "b"and whose third segment is "o". The name "bucket" denotes the secondsegment and "objectname" denotes the remainder of the path.

In general, a pattern looks like

[METHOD ][HOST]/[PATH]

All three parts are optional; "/" is a valid pattern.If METHOD is present, it must be followed by at least one space or tab.

Literal (that is, non-wildcard) parts of a pattern matchthe corresponding parts of a request case-sensitively.

A pattern with no method matches every method. A patternwith the method GET matches both GET and HEAD requests.Otherwise, the method must match exactly.

A pattern with no host matches every host.A pattern with a host matches URLs on that host only.

A path can include wildcard segments of the form {NAME} or {NAME...}.For example, "/b/{bucket}/o/{objectname...}".The wildcard name must be a valid Go identifier.Wildcards must be full path segments: they must be preceded by a slash and followed byeither a slash or the end of the string.For example, "/b_{bucket}" is not a valid pattern.

Normally a wildcard matches only a single path segment,ending at the next literal slash (not %2F) in the request URL.But if the "..." is present, then the wildcard matches the remainder of the URL path, including slashes.(Therefore it is invalid for a "..." wildcard to appear anywhere but at the end of a pattern.)The match for a wildcard can be obtained by callingRequest.PathValue with the wildcard's name.A trailing slash in a path acts as an anonymous "..." wildcard.

The special wildcard {$} matches only the end of the URL.For example, the pattern "/{$}" matches only the path "/",whereas the pattern "/" matches every path.

For matching, both pattern paths and incoming request paths are unescaped segment by segment.So, for example, the path "/a%2Fb/100%25" is treated as having two segments, "a/b" and "100%".The pattern "/a%2fb/" matches it, but the pattern "/a/b/" does not.

Precedence

If two or more patterns match a request, then the most specific pattern takes precedence.A pattern P1 is more specific than P2 if P1 matches a strict subset of P2’s requests;that is, if P2 matches all the requests of P1 and more.If neither is more specific, then the patterns conflict.There is one exception to this rule, for backwards compatibility:if two patterns would otherwise conflict and one has a host while the other does not,then the pattern with the host takes precedence.If a pattern passed toServeMux.Handle orServeMux.HandleFunc conflicts withanother pattern that is already registered, those functions panic.

As an example of the general rule, "/images/thumbnails/" is more specific than "/images/",so both can be registered.The former matches paths beginning with "/images/thumbnails/"and the latter will match any other path in the "/images/" subtree.

As another example, consider the patterns "GET /" and "/index.html":both match a GET request for "/index.html", but the former patternmatches all other GET and HEAD requests, while the latter matches anyrequest for "/index.html" that uses a different method.The patterns conflict.

Trailing-slash redirection

Consider aServeMux with a handler for a subtree, registered using a trailing slash or "..." wildcard.If the ServeMux receives a request for the subtree root without a trailing slash,it redirects the request by adding the trailing slash.This behavior can be overridden with a separate registration for the path withoutthe trailing slash or "..." wildcard. For example, registering "/images/" causes ServeMuxto redirect a request for "/images" to "/images/", unless "/images" hasbeen registered separately.

Request sanitizing

ServeMux also takes care of sanitizing the URL request path and the Hostheader, stripping the port number and redirecting any request containing . or.. segments or repeated slashes to an equivalent, cleaner URL.Escaped path elements such as "%2e" for "." and "%2f" for "/" are preservedand aren't considered separators for request routing.

Compatibility

The pattern syntax and matching behavior of ServeMux changed significantlyin Go 1.22. To restore the old behavior, set the GODEBUG environment variableto "httpmuxgo121=1". This setting is read once, at program startup; changesduring execution will be ignored.

The backwards-incompatible changes include:

  • Wildcards are just ordinary literal path segments in 1.21.For example, the pattern "/{x}" will match only that path in 1.21,but will match any one-segment path in 1.22.
  • In 1.21, no pattern was rejected, unless it was empty or conflicted with an existing pattern.In 1.22, syntactically invalid patterns will causeServeMux.Handle andServeMux.HandleFunc to panic.For example, in 1.21, the patterns "/{" and "/a{x}" match themselves,but in 1.22 they are invalid and will cause a panic when registered.
  • In 1.22, each segment of a pattern is unescaped; this was not done in 1.21.For example, in 1.22 the pattern "/%61" matches the path "/a" ("%61" being the URL escape sequence for "a"),but in 1.21 it would match only the path "/%2561" (where "%25" is the escape for the percent sign).
  • When matching patterns to paths, in 1.22 each segment of the path is unescaped; in 1.21, the entire path is unescaped.This change mostly affects how paths with %2F escapes adjacent to slashes are treated.Seehttps://go.dev/issue/21955 for details.

funcNewServeMux

func NewServeMux() *ServeMux

NewServeMux allocates and returns a newServeMux.

func (*ServeMux)Handle

func (mux *ServeMux) Handle(patternstring, handlerHandler)

Handle registers the handler for the given pattern.If the given pattern conflicts with one that is already registered, Handlepanics.

Example
package mainimport ("fmt""net/http")type apiHandler struct{}func (apiHandler) ServeHTTP(http.ResponseWriter, *http.Request) {}func main() {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(patternstring, handler func(ResponseWriter, *Request))

HandleFunc registers the handler function for the given pattern.If the given pattern conflicts with one that is already registered, HandleFuncpanics.

func (*ServeMux)Handleradded ingo1.1

func (mux *ServeMux) Handler(r *Request) (hHandler, patternstring)

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

The path and host are used unchanged for CONNECT requests.

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

If there is no registered handler that applies to the request,Handler returns a “page not found” or “method not supported”handler and an empty pattern.

Handler does not modify its argument. In particular, it does notpopulate named path wildcards, so r.PathValue will always returnthe empty string.

func (*ServeMux)ServeHTTP

func (mux *ServeMux) ServeHTTP(wResponseWriter, r *Request)

ServeHTTP dispatches the request to the handler whosepattern most closely matches the request URL.

typeServer

type Server struct {// Addr optionally specifies the TCP address for the server to listen on,// in the form "host:port". If empty, ":http" (port 80) is used.// The service names are defined inRFC 6335 and assigned by IANA.// See net.Dial for details of the address format.AddrstringHandlerHandler// handler to invoke, http.DefaultServeMux if nil// DisableGeneralOptionsHandler, if true, passes "OPTIONS *" requests to the Handler,// otherwise responds with 200 OK and Content-Length: 0.DisableGeneralOptionsHandlerbool// TLSConfig optionally provides a TLS configuration for use// by ServeTLS and ListenAndServeTLS. Note that this value is// cloned by ServeTLS and ListenAndServeTLS, so it's not// possible to modify the configuration with methods like// tls.Config.SetSessionTicketKeys. To use// SetSessionTicketKeys, use Server.Serve with a TLS Listener// instead.TLSConfig *tls.Config// ReadTimeout is the maximum duration for reading the entire// request, including the body. A zero or negative value means// there will be no timeout.//// Because ReadTimeout does not let Handlers make per-request// decisions on each request body's acceptable deadline or// upload rate, most users will prefer to use// ReadHeaderTimeout. It is valid to use them both.ReadTimeouttime.Duration// ReadHeaderTimeout is the amount of time allowed to read// request headers. The connection's read deadline is reset// after reading the headers and the Handler can decide what// is considered too slow for the body. If zero, the value of// ReadTimeout is used. If negative, or if zero and ReadTimeout// is zero or negative, there is no timeout.ReadHeaderTimeouttime.Duration// WriteTimeout is the maximum duration before timing out// writes of the response. It is reset whenever a new// request's header is read. Like ReadTimeout, it does not// let Handlers make decisions on a per-request basis.// A zero or negative value means there will be no timeout.WriteTimeouttime.Duration// IdleTimeout is the maximum amount of time to wait for the// next request when keep-alives are enabled. If zero, the value// of ReadTimeout is used. If negative, or if zero and ReadTimeout// is zero or negative, there is no timeout.IdleTimeouttime.Duration// MaxHeaderBytes controls the maximum number of bytes the// server will read parsing the request header's keys and// values, including the request line. It does not limit the// size of the request body.// If zero, DefaultMaxHeaderBytes is used.MaxHeaderBytesint// TLSNextProto optionally specifies a function to take over// ownership of the provided TLS connection when an ALPN// protocol upgrade has occurred. The map key is the protocol// name negotiated. The Handler argument should be used to// handle HTTP requests and will initialize the Request's TLS// and RemoteAddr if not already set. The connection is// automatically closed when the function returns.// If TLSNextProto is not nil, HTTP/2 support is not enabled// automatically.TLSNextProto map[string]func(*Server, *tls.Conn,Handler)// ConnState specifies an optional callback function that is// called when a client connection changes state. See the// ConnState type and associated constants for details.ConnState func(net.Conn,ConnState)// ErrorLog specifies an optional logger for errors accepting// connections, unexpected behavior from handlers, and// underlying FileSystem errors.// If nil, logging is done via the log package's standard logger.ErrorLog *log.Logger// BaseContext optionally specifies a function that returns// the base context for incoming requests on this server.// The provided Listener is the specific Listener that's// about to start accepting requests.// If BaseContext is nil, the default is context.Background().// If non-nil, it must return a non-nil context.BaseContext func(net.Listener)context.Context// ConnContext optionally specifies a function that modifies// the context used for a new connection c. The provided ctx// is derived from the base context and has a ServerContextKey// value.ConnContext func(ctxcontext.Context, cnet.Conn)context.Context// HTTP2 configures HTTP/2 connections.//// This field does not yet have any effect.// Seehttps://go.dev/issue/67813.HTTP2 *HTTP2Config// Protocols is the set of protocols accepted by the server.//// If Protocols includes UnencryptedHTTP2, the server will accept// unencrypted HTTP/2 connections. The server can serve both// HTTP/1 and unencrypted HTTP/2 on the same address and port.//// If Protocols is nil, the default is usually HTTP/1 and HTTP/2.// If TLSNextProto is non-nil and does not contain an "h2" entry,// the default is HTTP/1 only.Protocols *Protocols// 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)Closeadded ingo1.8

func (s *Server) Close()error

Close immediately closes all active net.Listeners and anyconnections in stateStateNew,StateActive, orStateIdle. For agraceful shutdown, useServer.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 theServer'sunderlying Listener(s).

func (*Server)ListenAndServe

func (s *Server) ListenAndServe()error

ListenAndServe listens on the TCP network address s.Addr and thencallsServe to handle requests on incoming connections.Accepted connections are configured to enable TCP keep-alives.

If s.Addr is blank, ":http" is used.

ListenAndServe always returns a non-nil error. AfterServer.Shutdown orServer.Close,the returned error isErrServerClosed.

func (*Server)ListenAndServeTLS

func (s *Server) ListenAndServeTLS(certFile, keyFilestring)error

ListenAndServeTLS listens on the TCP network address s.Addr andthen callsServeTLS 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 theserver must be provided if neither theServer's TLSConfig.Certificatesnor TLSConfig.GetCertificate are populated. If the certificate issigned by a certificate authority, the certFile should be theconcatenation of the server's certificate, any intermediates, andthe CA's certificate.

If s.Addr is blank, ":https" is used.

ListenAndServeTLS always returns a non-nil error. AfterServer.Shutdown orServer.Close, the returned error isErrServerClosed.

func (*Server)RegisterOnShutdownadded ingo1.9

func (s *Server) RegisterOnShutdown(f func())

RegisterOnShutdown registers a function to call onServer.Shutdown.This can be used to gracefully shutdown connections that haveundergone 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

func (s *Server) Serve(lnet.Listener)error

Serve accepts incoming connections on the Listener l, creating anew service goroutine for each. The service goroutines read requests andthen call s.Handler to reply to them.

HTTP/2 support is only enabled if the Listener returns*tls.Connconnections and they were configured with "h2" in the TLSConfig.NextProtos.

Serve always returns a non-nil error and closes l.AfterServer.Shutdown orServer.Close, the returned error isErrServerClosed.

func (*Server)ServeTLSadded ingo1.9

func (s *Server) ServeTLS(lnet.Listener, certFile, keyFilestring)error

ServeTLS accepts incoming connections on the Listener l, creating anew service goroutine for each. The service goroutines perform TLSsetup and then read requests, calling s.Handler to reply to them.

Files containing a certificate and matching private key for theserver must be provided if neither theServer'sTLSConfig.Certificates, TLSConfig.GetCertificate norconfig.GetConfigForClient are populated.If the certificate is signed by a certificate authority, thecertFile should be the concatenation of the server's certificate,any intermediates, and the CA's certificate.

ServeTLS always returns a non-nil error. AfterServer.Shutdown orServer.Close, thereturned error isErrServerClosed.

func (*Server)SetKeepAlivesEnabledadded ingo1.3

func (s *Server) SetKeepAlivesEnabled(vbool)

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

func (*Server)Shutdownadded ingo1.8

func (s *Server) Shutdown(ctxcontext.Context)error

Shutdown gracefully shuts down the server without interrupting anyactive connections. Shutdown works by first closing all openlisteners, then closing all idle connections, and then waitingindefinitely 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 anyerror returned from closing theServer's underlying Listener(s).

When Shutdown is called,Serve,ServeTLS,ListenAndServe, andListenAndServeTLS immediately returnErrServerClosed. Make sure theprogram doesn't exit and waits instead for Shutdown to return.

Shutdown does not attempt to close nor wait for hijackedconnections such as WebSockets. The caller of Shutdown shouldseparately notify such long-lived connections of shutdown and waitfor them to close, if desired. SeeServer.RegisterOnShutdown for a way toregister shutdown notification functions.

Once Shutdown has been called on a server, it may not be reused;future calls to methods such as Serve will return ErrServerClosed.

Example
package mainimport ("context""log""net/http""os""os/signal")func main() {var srv http.ServeridleConnsClosed := make(chan struct{})go func() {sigint := make(chan os.Signal, 1)signal.Notify(sigint, os.Interrupt)<-sigint// We received an interrupt signal, shut down.if err := srv.Shutdown(context.Background()); err != nil {// Error from closing listeners, or context timeout:log.Printf("HTTP server Shutdown: %v", err)}close(idleConnsClosed)}()if err := srv.ListenAndServe(); err != http.ErrServerClosed {// Error starting or closing listener:log.Fatalf("HTTP server ListenAndServe: %v", err)}<-idleConnsClosed}

typeTransport

type Transport struct {// Proxy specifies a function to return a proxy for a given// Request. If the function returns a non-nil error, the// request is aborted with the provided error.//// The proxy type is determined by the URL scheme. "http",// "https", "socks5", and "socks5h" are supported. If the scheme is empty,// "http" is assumed.// "socks5" is treated the same as "socks5h".//// If the proxy URL contains a userinfo subcomponent,// the proxy request will pass the username and password// in a Proxy-Authorization header.//// If Proxy is nil or returns a nil *URL, no proxy is used.Proxy func(*Request) (*url.URL,error)// OnProxyConnectResponse is called when the Transport gets an HTTP response from// a proxy for a CONNECT request. It's called before the check for a 200 OK response.// If it returns an error, the request fails with that error.OnProxyConnectResponse func(ctxcontext.Context, proxyURL *url.URL, connectReq *Request, connectRes *Response)error// DialContext specifies the dial function for creating unencrypted TCP connections.// If DialContext is nil (and the deprecated Dial below is also nil),// then the transport dials using package net.//// DialContext runs concurrently with calls to RoundTrip.// A RoundTrip call that initiates a dial may end up using// a connection dialed previously when the earlier connection// becomes idle before the later DialContext completes.DialContext func(ctxcontext.Context, network, addrstring) (net.Conn,error)// Dial specifies the dial function for creating unencrypted TCP connections.//// Dial runs concurrently with calls to RoundTrip.// A RoundTrip call that initiates a dial may end up using// a connection dialed previously when the earlier connection// becomes idle before the later Dial completes.//// Deprecated: Use DialContext instead, which allows the transport// to cancel dials as soon as they are no longer needed.// If both are set, DialContext takes priority.Dial func(network, addrstring) (net.Conn,error)// DialTLSContext specifies an optional dial function for creating// TLS connections for non-proxied HTTPS requests.//// If DialTLSContext is nil (and the deprecated DialTLS below is also nil),// DialContext and TLSClientConfig are used.//// If DialTLSContext is set, the Dial and DialContext hooks are not used for HTTPS// requests and the TLSClientConfig and TLSHandshakeTimeout// are ignored. The returned net.Conn is assumed to already be// past the TLS handshake.DialTLSContext func(ctxcontext.Context, network, addrstring) (net.Conn,error)// DialTLS specifies an optional dial function for creating// TLS connections for non-proxied HTTPS requests.//// Deprecated: Use DialTLSContext instead, which allows the transport// to cancel dials as soon as they are no longer needed.// If both are set, DialTLSContext takes priority.DialTLS func(network, addrstring) (net.Conn,error)// TLSClientConfig specifies the TLS configuration to use with// tls.Client.// If nil, the default configuration is used.// If non-nil, HTTP/2 support may not be enabled by default.TLSClientConfig *tls.Config// TLSHandshakeTimeout specifies the maximum amount of time to// wait for a TLS handshake. Zero means no timeout.TLSHandshakeTimeouttime.Duration// DisableKeepAlives, if true, disables HTTP keep-alives and// will only use the connection to the server for a single// HTTP request.//// This is unrelated to the similarly named TCP keep-alives.DisableKeepAlivesbool// DisableCompression, if true, prevents the Transport from// requesting compression with an "Accept-Encoding: gzip"// request header when the Request contains no existing// Accept-Encoding value. If the Transport requests gzip on// its own and gets a gzipped response, it's transparently// decoded in the Response.Body. However, if the user// explicitly requested gzip it is not automatically// uncompressed.DisableCompressionbool// MaxIdleConns controls the maximum number of idle (keep-alive)// connections across all hosts. Zero means no limit.MaxIdleConnsint// MaxIdleConnsPerHost, if non-zero, controls the maximum idle// (keep-alive) connections to keep per-host. If zero,// DefaultMaxIdleConnsPerHost is used.MaxIdleConnsPerHostint// MaxConnsPerHost optionally limits the total number of// connections per host, including connections in the dialing,// active, and idle states. On limit violation, dials will block.//// Zero means no limit.MaxConnsPerHostint// IdleConnTimeout is the maximum amount of time an idle// (keep-alive) connection will remain idle before closing// itself.// Zero means no limit.IdleConnTimeouttime.Duration// ResponseHeaderTimeout, if non-zero, specifies the amount of// time to wait for a server's response headers after fully// writing the request (including its body, if any). This// time does not include the time to read the response body.ResponseHeaderTimeouttime.Duration// ExpectContinueTimeout, if non-zero, specifies the amount of// time to wait for a server's first response headers after fully// writing the request headers if the request has an// "Expect: 100-continue" header. Zero means no timeout and// causes the body to be sent immediately, without// waiting for the server to approve.// This time does not include the time to send the request header.ExpectContinueTimeouttime.Duration// TLSNextProto specifies how the Transport switches to an// alternate protocol (such as HTTP/2) after a TLS ALPN// protocol negotiation. If Transport dials a TLS connection// with a non-empty protocol name and TLSNextProto contains a// map entry for that key (such as "h2"), then the func is// called with the request's authority (such as "example.com"// or "example.com:1234") and the TLS connection. The function// must return a RoundTripper that then handles the request.// If TLSNextProto is not nil, HTTP/2 support is not enabled// automatically.TLSNextProto map[string]func(authoritystring, c *tls.Conn)RoundTripper// ProxyConnectHeader optionally specifies headers to send to// proxies during CONNECT requests.// To set the header dynamically, see GetProxyConnectHeader.ProxyConnectHeaderHeader// GetProxyConnectHeader optionally specifies a func to return// headers to send to proxyURL during a CONNECT request to the// ip:port target.// If it returns an error, the Transport's RoundTrip fails with// that error. It can return (nil, nil) to not add headers.// If GetProxyConnectHeader is non-nil, ProxyConnectHeader is// ignored.GetProxyConnectHeader func(ctxcontext.Context, proxyURL *url.URL, targetstring) (Header,error)// MaxResponseHeaderBytes specifies a limit on how many// response bytes are allowed in the server's response// header.//// Zero means to use a default limit.MaxResponseHeaderBytesint64// WriteBufferSize specifies the size of the write buffer used// when writing to the transport.// If zero, a default (currently 4KB) is used.WriteBufferSizeint// ReadBufferSize specifies the size of the read buffer used// when reading from the transport.// If zero, a default (currently 4KB) is used.ReadBufferSizeint// ForceAttemptHTTP2 controls whether HTTP/2 is enabled when a non-zero// Dial, DialTLS, or DialContext func or TLSClientConfig is provided.// By default, use of any those fields conservatively disables HTTP/2.// To use a custom dialer or TLS config and still attempt HTTP/2// upgrades, set this to true.ForceAttemptHTTP2bool// HTTP2 configures HTTP/2 connections.//// This field does not yet have any effect.// Seehttps://go.dev/issue/67813.HTTP2 *HTTP2Config// Protocols is the set of protocols supported by the transport.//// If Protocols includes UnencryptedHTTP2 and does not include HTTP1,// the transport will use unencrypted HTTP/2 for requests for http:// URLs.//// If Protocols is nil, the default is usually HTTP/1 only.// If ForceAttemptHTTP2 is true, or if TLSNextProto contains an "h2" entry,// the default is HTTP/1 and HTTP/2.Protocols *Protocols// contains filtered or unexported fields}

Transport is an implementation ofRoundTripper 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 usingTransport.CloseIdleConnections methodand the [Transport.MaxIdleConnsPerHost] and [Transport.DisableKeepAlives] fields.

Transports should be reused instead of created as needed.Transports are safe for concurrent use by multiple goroutines.

A Transport is a low-level primitive for making HTTP and HTTPS requests.For high-level functionality, such as cookies and redirects, seeClient.

Transport uses HTTP/1.1 for HTTP URLs and either HTTP/1.1 or HTTP/2for HTTPS URLs, depending on whether the server supports HTTP/2,and how the Transport is configured. TheDefaultTransport supports HTTP/2.To explicitly enable HTTP/2 on a transport, set [Transport.Protocols].

Responses with status codes in the 1xx range are either handledautomatically (100 expect-continue) or ignored. The oneexception is HTTP status code 101 (Switching Protocols), which isconsidered a terminal status and returned byTransport.RoundTrip. To see theignored 1xx responses, use the httptrace trace package'sClientTrace.Got1xxResponse.

Transport only retries a request upon encountering a network errorif the connection has been already been used successfully and if therequest is idempotent and either has no body or has its [Request.GetBody]defined. HTTP requests are considered idempotent if they have HTTP methodsGET, HEAD, OPTIONS, or TRACE; or if theirHeader map contains an"Idempotency-Key" or "X-Idempotency-Key" entry. If the idempotency keyvalue is a zero-length slice, the request is treated as idempotent but theheader is not sent on the wire.

func (*Transport)CancelRequestdeprecatedadded ingo1.1

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

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

Deprecated: UseRequest.WithContext to create a request with acancelable context instead. CancelRequest cannot cancel HTTP/2requests. This may become a no-op in a future release of Go.

func (*Transport)Cloneadded ingo1.13

func (t *Transport) Clone() *Transport

Clone returns a deep copy of t's exported fields.

func (*Transport)CloseIdleConnections

func (t *Transport) CloseIdleConnections()

CloseIdleConnections closes any connections which were previouslyconnected from previous requests but are now sitting idle ina "keep-alive" state. It does not interrupt any connections currentlyin use.

func (*Transport)RegisterProtocol

func (t *Transport) RegisterProtocol(schemestring, rtRoundTripper)

RegisterProtocol registers a new protocol with scheme.TheTransport 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 provideimplementations of protocol schemes like "ftp" or "file".

If rt.RoundTrip returnsErrSkipAltProtocol, the Transport willhandle theTransport.RoundTrip itself for that one request, as if theprotocol were not registered.

func (*Transport)RoundTrip

func (t *Transport) RoundTrip(req *Request) (*Response,error)

RoundTrip implements theRoundTripper interface.

For higher-level HTTP client support (such as handling of cookiesand redirects), seeGet,Post, and theClient type.

Like the RoundTripper interface, the error types returnedby RoundTrip are unspecified.

Source Files

View all Source files

Directories

PathSynopsis
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 internal contains HTTP internals shared by net/http and net/http/httputil.
Package internal contains HTTP internals shared by net/http and net/http/httputil.
testcert
Package testcert contains a test-only localhost certificate.
Package testcert contains a test-only localhost certificate.
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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp