Involved Source Filesclient.goclone.gocookie.go Package http provides HTTP client and server implementations.
Get, Head, Post, and PostForm make HTTP (or HTTPS) requests:
resp, err := http.Get("http://example.com/")
...
resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf)
...
resp, err := http.PostForm("http://example.com/form",
url.Values{"key": {"Value"}, "id": {"123"}})
The 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 other
settings, create a Client:
client := &http.Client{
CheckRedirect: redirectPolicyFunc,
}
resp, err := client.Get("http://example.com")
// ...
req, err := http.NewRequest("GET", "http://example.com", nil)
// ...
req.Header.Add("If-None-Match", `W/"wyzzy"`)
resp, err := client.Do(req)
// ...
For control over proxies, TLS configuration, keep-alives,
compression, and other settings, create a Transport:
tr := &http.Transport{
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 multiple
goroutines 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 use DefaultServeMux.
Handle and HandleFunc add handlers to DefaultServeMux:
http.Handle("/foo", fooHandler)
http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
})
log.Fatal(http.ListenAndServe(":8080", nil))
More control over the server's behavior is available by creating a
custom Server:
s := &http.Server{
Addr: ":8080",
Handler: myHandler,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
log.Fatal(s.ListenAndServe())
# HTTP/2
Starting with Go 1.6, the http package has transparent support for the
HTTP/2 protocol when using HTTPS. Programs that must disable HTTP/2
can do so by setting Transport.TLSNextProto (for clients) or
Server.TLSNextProto (for servers) to a non-nil, empty
map. Alternatively, the following GODEBUG settings are
currently supported:
GODEBUG=http2client=0 # disable HTTP/2 client support
GODEBUG=http2server=0 # disable HTTP/2 server support
GODEBUG=http2debug=1 # enable verbose HTTP/2 debug logs
GODEBUG=http2debug=2 # ... even more verbose, with frame dumps
Please report any issues before disabling HTTP/2 support: https://golang.org/s/http2bug
The http package's Transport and Server both automatically enable
HTTP/2 support for simple configurations. To enable HTTP/2 for more
complex configurations, to use lower-level HTTP/2 features, or to use
a newer version of Go's http2 package, import "golang.org/x/net/http2"
directly and use its ConfigureTransport and/or ConfigureServer
functions. Manually configuring HTTP/2 via the golang.org/x/net/http2
package takes precedence over the net/http package's built-in HTTP/2
support.filetransport.gofs.goh2_bundle.goh2_error.goheader.gohttp.gojar.gomethod.gorequest.goresponse.goresponsecontroller.goroundtrip.goserver.gosniff.gosocks_bundle.gostatus.gotransfer.gotransport.gotransport_default_other.go
Code Examples
package main
import (
"log"
"net/http"
)
func main() {
// Simple static webserver:
log.Fatal(http.ListenAndServe(":8080", http.FileServer(http.Dir("/usr/share/doc"))))
}
package main
import (
"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 files
if !strings.HasPrefix(file.Name(), ".") {
fis = append(fis, file)
}
}
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 response
return nil, fs.ErrPermission
}
file, err := fsys.FileSystem.Open(name)
if err != nil {
return nil, err
}
return dotFileHidingFile{file}, err
}
func main() {
fsys := dotFileHidingFileSystem{http.Dir(".")}
http.Handle("/", http.FileServer(fsys))
log.Fatal(http.ListenAndServe(":8080", nil))
}
package main
import (
"net/http"
)
func main() {
// To serve a directory on disk (/tmp) under an alternate URL
// path (/tmpfiles/), use StripPrefix to modify the request
// URL's path before the FileServer sees it:
http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
}
package main
import (
"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)
}
package main
import (
"fmt"
"log"
"net/http"
"sync"
)
type countHandler struct {
mu sync.Mutex // guards n
n 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))
}
package main
import (
"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))
}
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/hijack", func(w http.ResponseWriter, r *http.Request) {
hj, ok := w.(http.Hijacker)
if !ok {
http.Error(w, "webserver doesn't support hijacking", http.StatusInternalServerError)
return
}
conn, bufrw, err := hj.Hijack()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Don't forget to close the connection:
defer conn.Close()
bufrw.WriteString("Now we're speaking raw TCP. Say hi: ")
bufrw.Flush()
s, err := bufrw.ReadString('\n')
if err != nil {
log.Printf("error reading string: %v", err)
return
}
fmt.Fprintf(bufrw, "You said: %q\nBye.\n", s)
bufrw.Flush()
})
}
package main
import (
"io"
"log"
"net/http"
)
func main() {
// Hello world, the web server
helloHandler := func(w http.ResponseWriter, req *http.Request) {
io.WriteString(w, "Hello, world!\n")
}
http.HandleFunc("/hello", helloHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
package main
import (
"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)
}
package main
import (
"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 404
mux.Handle("/resources", http.NotFoundHandler())
// Create sample handler that returns 200
mux.Handle("/resources/people/", newPeopleHandler())
log.Fatal(http.ListenAndServe(":8080", mux))
}
package main
import (
"io"
"net/http"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/sendstrailers", func(w http.ResponseWriter, req *http.Request) {
// Before any call to WriteHeader or Write, declare
// the trailers you will set during the HTTP
// response. These three headers are actually sent in
// the trailer.
w.Header().Set("Trailer", "AtEnd1, AtEnd2")
w.Header().Add("Trailer", "AtEnd3")
w.Header().Set("Content-Type", "text/plain; charset=utf-8") // normal header
w.WriteHeader(http.StatusOK)
w.Header().Set("AtEnd1", "value 1")
io.WriteString(w, "This HTTP response has both headers before this text and trailers at the end.\n")
w.Header().Set("AtEnd2", "value 2")
w.Header().Set("AtEnd3", "value 3") // These will appear as trailers.
})
}
package main
import (
"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!")
})
}
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
)
func main() {
var srv http.Server
idleConnsClosed := 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
}
package main
import (
"net/http"
)
func main() {
// To serve a directory on disk (/tmp) under an alternate URL
// path (/tmpfiles/), use StripPrefix to modify the request
// URL's path before the FileServer sees it:
http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
}
Package-Level Type Names (total 229, in which 26 are exported)
/* sort exporteds by: | */
A Client is an HTTP client. Its zero value (DefaultClient) is a
usable client that uses DefaultTransport.
The Client's Transport typically has internal state (cached TCP
connections), so Clients should be reused instead of created as
needed. Clients are safe for concurrent use by multiple goroutines.
A Client is higher-level than a RoundTripper (such as Transport)
and additionally handles HTTP details such as cookies and
redirects.
When following redirects, the Client will forward all headers set on the
initial Request except:
• when forwarding sensitive headers like "Authorization",
"WWW-Authenticate", and "Cookie" to untrusted targets.
These headers will be ignored when following a redirect to a domain
that is not a subdomain match or exact match of the initial domain.
For example, a redirect from "foo.com" to either "foo.com" or "sub.foo.com"
will forward the sensitive headers, but a redirect to "bar.com" will not.
• when forwarding the "Cookie" header with a non-nil cookie Jar.
Since each redirect may mutate the state of the cookie jar,
a redirect may possibly alter a cookie set in the initial request.
When forwarding the "Cookie" header, any mutated cookies will be omitted,
with the expectation that the Jar will insert those mutated cookies
with the updated values (assuming the origin matches).
If Jar is nil, the initial cookies are forwarded without change. 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. 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. 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. Transport specifies the mechanism by which individual
HTTP requests are made.
If nil, DefaultTransport is used. CloseIdleConnections closes any connections on its Transport which
were previously connected from previous requests but are now
sitting idle in a "keep-alive" state. It does not interrupt any
connections currently in use.
If the Client's Transport does not have a CloseIdleConnections method
then this method does nothing. Do sends an HTTP request and returns an HTTP response, following
policy (such as redirects, cookies, auth) as configured on the
client.
An error is returned if caused by client policy (such as
CheckRedirect), or failure to speak HTTP (such as a network
connectivity problem). A non-2xx status code doesn't cause an
error.
If the returned error is nil, the Response will contain a non-nil
Body which the user is expected to close. If the Body is not both
read to EOF and closed, the Client's underlying RoundTripper
(typically Transport) may not be able to re-use a persistent TCP
connection to the server for a subsequent "keep-alive" request.
The request Body, if non-nil, will be closed by the underlying
Transport, even on errors.
On error, any Response can be ignored. A non-nil Response with a
non-nil error only occurs when CheckRedirect fails, and even then
the returned Response.Body is already closed.
Generally Get, Post, or PostForm will be used instead of Do.
If the server replies with a redirect, the Client first uses the
CheckRedirect function to determine whether the redirect should be
followed. If permitted, a 301, 302, or 303 redirect causes
subsequent requests to use HTTP method GET
(or HEAD if the original request was HEAD), with no body.
A 307 or 308 redirect preserves the original HTTP method and body,
provided that the Request.GetBody function is defined.
The NewRequest function automatically sets GetBody for common
standard library body types.
Any returned error will be of type *url.Error. The url.Error
value's Timeout method will report true if the request timed out. Get issues a GET to the specified URL. If the response is one of the
following redirect codes, Get follows the redirect after calling the
Client's CheckRedirect function:
301 (Moved Permanently)
302 (Found)
303 (See Other)
307 (Temporary Redirect)
308 (Permanent Redirect)
An error is returned if the Client's CheckRedirect function fails
or if there was an HTTP protocol error. A non-2xx response doesn't
cause an error. Any returned error will be of type *url.Error. The
url.Error value's Timeout method will report true if the request
timed out.
When err is nil, resp always contains a non-nil resp.Body.
Caller should close resp.Body when done reading from it.
To make a request with custom headers, use NewRequest and Client.Do.
To make a request with a specified context.Context, use NewRequestWithContext
and Client.Do. Head issues a HEAD to the specified URL. If the response is one of the
following redirect codes, Head follows the redirect after calling the
Client's CheckRedirect function:
301 (Moved Permanently)
302 (Found)
303 (See Other)
307 (Temporary Redirect)
308 (Permanent Redirect)
To make a request with a specified context.Context, use NewRequestWithContext
and Client.Do. Post issues a POST to the specified URL.
Caller should close resp.Body when done reading from it.
If the provided body is an io.Closer, it is closed after the
request.
To set custom headers, use NewRequest and Client.Do.
To make a request with a specified context.Context, use NewRequestWithContext
and Client.Do.
See the Client.Do method documentation for details on how redirects
are handled. PostForm issues a POST to the specified URL,
with data's keys and values URL-encoded as the request body.
The Content-Type header is set to application/x-www-form-urlencoded.
To set other headers, use NewRequest and Client.Do.
When err is nil, resp always contains a non-nil resp.Body.
Caller should close resp.Body when done reading from it.
See the Client.Do method documentation for details on how redirects
are handled.
To make a request with a specified context.Context, use NewRequestWithContext
and Client.Do. checkRedirect calls either the user's configured CheckRedirect
function, or the default.(*Client) deadline() time.Time(*Client) do(req *Request) (retres *Response, reterr error) makeHeadersCopier makes a function that copies headers from the
initial Request, ireq. For every redirect, this function must be called
so that it can copy headers into the upcoming Request. didTimeout is non-nil only if err != nil.(*Client) transport() RoundTripper
*Client : h2Transport
var DefaultClient *Client
The CloseNotifier interface is implemented by ResponseWriters which
allow detecting when the underlying connection has gone away.
This mechanism can be used to cancel long operations on the server
if the client has disconnected before the response is ready.
Deprecated: the CloseNotifier interface predates Go's context package.
New code should use Request.Context instead. 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 a 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.
*http2responseWriter
*response
A Cookie represents an HTTP cookie as sent in the Set-Cookie header of an
HTTP response or the Cookie header of an HTTP request.
See https://tools.ietf.org/html/rfc6265 for details. // optional // optionalHttpOnlybool 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 secondsNamestring // optionalRawstring // for reading cookies onlySameSiteSameSiteSecurebool // Raw text of unparsed attribute-value pairsValuestring String returns the serialization of the cookie for use in a Cookie
header (if only Name and Value are set) or a Set-Cookie response
header (if other fields are set).
If c is nil or c.Name is invalid, the empty string is returned. Valid reports whether the cookie is valid.
*Cookie : fmt.Stringer
*Cookie : context.stringer
*Cookie : runtime.stringer
func CookieJar.Cookies(u *url.URL) []*Cookie
func (*Request).Cookie(name string) (*Cookie, error)
func (*Request).Cookies() []*Cookie
func (*Response).Cookies() []*Cookie
func readCookies(h Header, filter string) []*Cookie
func readSetCookies(h Header) []*Cookie
func SetCookie(w ResponseWriter, cookie *Cookie)
func CookieJar.SetCookies(u *url.URL, cookies []*Cookie)
func (*Request).AddCookie(c *Cookie)
A CookieJar manages storage and use of cookies in HTTP requests.
Implementations of CookieJar must be safe for concurrent use by multiple
goroutines.
The net/http/cookiejar package provides a CookieJar implementation. 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 in RFC 6265. 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.
A Dir implements FileSystem using the native file system restricted to a
specific directory tree.
While the FileSystem.Open method takes '/'-separated paths, a Dir's string
value is a filename on the native file system, not a URL, so it is separated
by filepath.Separator, which isn't necessarily '/'.
Note that Dir could expose sensitive files and directories. Dir will follow
symlinks pointing out of the directory tree, which can be especially dangerous
if serving from a directory in which users are able to create arbitrary symlinks.
Dir will also allow access to files and directories starting with a period,
which could expose sensitive directories like .git or sensitive files like
.htpasswd. To exclude files with a leading period, remove the files/directories
from the server or create a custom FileSystem implementation.
An empty Dir is treated as ".". Open implements FileSystem using os.Open, opening files for reading rooted
and relative to the directory d.
Dir : FileSystem
A FileSystem implements access to a collection of named files.
The elements in a file path are separated by slash ('/', U+002F)
characters, regardless of host operating system convention.
See the FileServer function to convert a FileSystem to a Handler.
This interface predates the fs.FS interface, which can be used instead:
the FS adapter function converts an fs.FS to a FileSystem.( FileSystem) Open(name string) (File, error)DirioFS
func FS(fsys fs.FS) FileSystem
func FileServer(root FileSystem) Handler
func NewFileTransport(fs FileSystem) RoundTripper
func serveFile(w ResponseWriter, r *Request, fs FileSystem, name string, redirect bool)
The Flusher interface is implemented by ResponseWriters that allow
an HTTP handler to flush buffered data to the client.
The default HTTP/1.x and HTTP/2 ResponseWriter implementations
support Flusher, but ResponseWriter wrappers may not. Handlers
should always test for this ability at runtime.
Note that even for ResponseWriters that support Flush,
if the client is connected through an HTTP proxy,
the buffered data may not reach the client until the response
completes. Flush sends any buffered data to the client.
*http2responseWriter
*response
The HandlerFunc type is an adapter to allow the use of
ordinary functions as HTTP handlers. If f is a function
with the appropriate signature, HandlerFunc(f) is a
Handler that calls f. ServeHTTP calls f(w, r).
HandlerFunc : Handler
func http2new400Handler(err error) HandlerFunc
A Header represents the key-value pairs in an HTTP header.
The keys should be in canonical form, as returned by
CanonicalHeaderKey. 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 by
CanonicalHeaderKey. Clone returns a copy of h or nil if h is nil. Del deletes the values associated with key.
The key is case insensitive; it is canonicalized by
CanonicalHeaderKey. Get gets the first value associated with the given key. If
there are no values associated with the key, Get returns "".
It is case insensitive; textproto.CanonicalMIMEHeaderKey is
used to canonicalize the provided key. Get assumes that all
keys are stored in canonical form. To use non-canonical keys,
access the map directly. Set sets the header entries associated with key to the
single element value. It replaces any existing values
associated with key. The key is case insensitive; it is
canonicalized by textproto.CanonicalMIMEHeaderKey.
To use non-canonical keys, assign to the map directly. Values returns all values associated with the given key.
It is case insensitive; textproto.CanonicalMIMEHeaderKey is
used to canonicalize the provided key. To use non-canonical
keys, access the map directly.
The returned slice is not a copy. Write writes a header in wire format. 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. get is like Get, but key must already be in CanonicalHeaderKey form. has reports whether h has the provided key defined, even if it's
set to 0-length slice. sortedKeyValues returns h's keys sorted in the returned kvs
slice. The headerSorter used to sort is also returned, for possible
return to headerSorterCache.( Header) write(w io.Writer, trace *httptrace.ClientTrace) error( Header) writeSubset(w io.Writer, exclude map[string]bool, trace *httptrace.ClientTrace) error
func Header.Clone() Header
func ResponseWriter.Header() Header
func cloneOrMakeHeader(hdr Header) Header
func fixTrailer(header Header, chunked bool) (Header, error)
func http2cloneHeader(h Header) Header
func cloneOrMakeHeader(hdr Header) Header
func fixLength(isResponse bool, status int, requestMethod string, header Header, chunked bool) (int64, error)
func fixPragmaCacheControl(header Header)
func fixTrailer(header Header, chunked bool) (Header, error)
func http2checkValidHTTP2RequestHeaders(h Header) error
func http2cloneHeader(h Header) Header
func http2encodeHeaders(enc *hpack.Encoder, h Header, keys []string)
func isProtocolSwitchHeader(h Header) bool
func isProtocolSwitchResponse(code int, h Header) bool
func mergeSetHeader(dst *Header, src Header)
func mergeSetHeader(dst *Header, src Header)
func readCookies(h Header, filter string) []*Cookie
func readSetCookies(h Header) []*Cookie
func shouldClose(major, minor int, header Header, removeCloseHeader bool) bool
func (*Request).write(w io.Writer, usingProxy bool, extraHeaders Header, waitForContinue func() bool) (err error)
func nhooyr.io/websocket.headerContainsTokenIgnoreCase(h Header, key, token string) bool
func nhooyr.io/websocket.headerTokens(h Header, key string) []string
func nhooyr.io/websocket.verifyServerExtensions(copts *websocket.compressionOptions, h Header) (*websocket.compressionOptions, error)
func nhooyr.io/websocket.websocketExtensions(h Header) []websocket.websocketExtension
The Hijacker interface is implemented by ResponseWriters that allow
an HTTP handler to take over the connection.
The default ResponseWriter for HTTP/1.x connections supports
Hijacker, but HTTP/2 connections intentionally do not.
ResponseWriter wrappers may also not support Hijacker. Handlers
should always test for this ability at runtime. 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.
*ResponseController
*response
MaxBytesError is returned by MaxBytesReader when its read limit is exceeded.Limitint64(*MaxBytesError) Error() string
*MaxBytesError : error
Pusher is the interface implemented by ResponseWriters that support
HTTP/2 server push. For more background, see
https://tools.ietf.org/html/rfc7540#section-8.2. 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.
*http2responseWriter
*timeoutWriter
PushOptions describes options for Pusher.Push. Header specifies additional promised request headers. This cannot
include HTTP/2 pseudo header fields like ":path" and ":scheme",
which will be added automatically. Method specifies the HTTP method for the promised request.
If set, it must be "GET" or "HEAD". Empty means "GET".
func Pusher.Push(target string, opts *PushOptions) error
A Request represents an HTTP request received by a server
or to be sent by a client.
The field semantics differ slightly between client and server
usage. In addition to the notes on the fields below, see the
documentation for Request.Write and RoundTripper. 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. 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. 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. 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. 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. 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. 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. For server requests, Host specifies the host on which the
URL is sought. For HTTP/1 (per RFC 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. Method specifies the HTTP method (GET, POST, PUT, etc.).
For client requests, an empty string means GET.
Go's HTTP client does not support sending a request with
the CONNECT method. See the documentation on Transport for
details. 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. 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. 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. // "HTTP/1.0" // 1 // 0 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. 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. Response is the redirect response which caused this request
to be created. This field is only populated during client
redirects. 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. 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. 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. 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. (See RFC 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. ctx is either the client or server context. It should only
be modified via copying the whole Request using Clone or WithContext.
It is unexported to prevent people from using Context wrong
and mutating the contexts held by callers of the same request. AddCookie adds a cookie to the request. Per RFC 6265 section 5.4,
AddCookie does not attach more than one Cookie header field. That
means all cookies, if any, are written into the same line,
separated by semicolon.
AddCookie only sanitizes c's name and value, and does not sanitize
a Cookie header already present in the request. BasicAuth returns the username and password provided in the request's
Authorization header, if the request uses HTTP Basic Authentication.
See RFC 2617, Section 2. Clone returns a deep copy of r with its context changed to ctx.
The provided ctx must be non-nil.
For an outgoing client request, the context controls the entire
lifetime of a request and its response: obtaining a connection,
sending the request, and reading the response headers and body. Context returns the request's context. To change the context, use
Clone or WithContext.
The returned context is always non-nil; it defaults to the
background context.
For outgoing client requests, the context controls cancellation.
For incoming server requests, the context is canceled when the
client's connection closes, the request is canceled (with HTTP/2),
or when the ServeHTTP method returns. Cookie returns the named cookie provided in the request or
ErrNoCookie if not found.
If multiple cookies match the given name, only one cookie will
be returned. Cookies parses and returns the HTTP cookies sent with the request. FormFile returns the first file for the provided form key.
FormFile calls ParseMultipartForm and ParseForm if necessary. FormValue returns the first value for the named component of the query.
POST and PUT body parameters take precedence over URL query string values.
FormValue calls ParseMultipartForm and ParseForm if necessary and ignores
any errors returned by these functions.
If key is not present, FormValue returns the empty string.
To access multiple values of the same key, call ParseForm and
then inspect Request.Form directly. MultipartReader returns a MIME multipart reader if this is a
multipart/form-data or a multipart/mixed POST request, else returns nil and an error.
Use this function instead of ParseMultipartForm to
process the request body as a stream. ParseForm populates r.Form and r.PostForm.
For all requests, ParseForm parses the raw query from the URL and updates
r.Form.
For POST, PUT, and PATCH requests, it also reads the request body, parses it
as a form and puts the results into both r.PostForm and r.Form. Request body
parameters take precedence over URL query string values in r.Form.
If the request Body's size has not already been limited by MaxBytesReader,
the size is capped at 10MB.
For other HTTP methods, or when the Content-Type is not
application/x-www-form-urlencoded, the request Body is not read, and
r.PostForm is initialized to a non-nil, empty value.
ParseMultipartForm calls ParseForm automatically.
ParseForm is idempotent. ParseMultipartForm parses a request body as multipart/form-data.
The whole request body is parsed and up to a total of maxMemory bytes of
its file parts are stored in memory, with the remainder stored on
disk in temporary files.
ParseMultipartForm calls ParseForm if necessary.
If ParseForm returns an error, ParseMultipartForm returns it but also
continues parsing the request body.
After one call to ParseMultipartForm, subsequent calls have no effect. PostFormValue returns the first value for the named component of the POST,
PATCH, or PUT request body. URL query parameters are ignored.
PostFormValue calls ParseMultipartForm and ParseForm if necessary and ignores
any errors returned by these functions.
If key is not present, PostFormValue returns the empty string. ProtoAtLeast reports whether the HTTP protocol used
in the request is at least major.minor. Referer returns the referring URL, if sent in the request.
Referer is misspelled as in the request itself, a mistake from the
earliest days of HTTP. This value can also be fetched from the
Header map as Header["Referer"]; the benefit of making it available
as a method is that the compiler can diagnose programs that use the
alternate (correct English) spelling req.Referrer() but cannot
diagnose programs that use Header["Referrer"]. SetBasicAuth sets the request's Authorization header to use HTTP
Basic Authentication with the provided username and password.
With HTTP Basic Authentication the provided username and password
are not encrypted. It should generally only be used in an HTTPS
request.
The username may not contain a colon. Some protocols may impose
additional requirements on pre-escaping the username and
password. For instance, when used with OAuth2, both arguments must
be URL encoded first with url.QueryEscape. UserAgent returns the client's User-Agent, if sent in the request. WithContext returns a shallow copy of r with its context changed
to ctx. The provided ctx must be non-nil.
For outgoing client request, the context controls the entire
lifetime of a request and its response: obtaining a connection,
sending the request, and reading the response headers and body.
To create a new request with a context, use NewRequestWithContext.
To make a deep copy of a request with a new context, use Request.Clone. Write writes an HTTP/1.1 request, which is the header and body, in wire format.
This method consults the following fields of the request:
Host
URL
Method (defaults to "GET")
Header
ContentLength
TransferEncoding
Body
If Body is present, Content-Length is <= 0 and TransferEncoding
hasn't been set to "identity", Write adds "Transfer-Encoding:
chunked" to the header. Body is closed after it is sent. WriteProxy is like Write but writes the request in the form
expected by an HTTP proxy. In particular, WriteProxy writes the
initial Request-URI line of the request with an absolute URI, per
section 5.3 of RFC 7230, including the scheme and host.
In either case, WriteProxy also writes a Host header, using
either r.Host or r.URL.Host.(*Request) closeBody() error(*Request) expectsContinue() bool isH2Upgrade reports whether r represents the http2 "client preface"
magic string.(*Request) isReplayable() bool(*Request) multipartReader(allowMixed bool) (*multipart.Reader, error) outgoingLength reports the Content-Length of this outgoing (Client) request.
It maps 0 into -1 (unknown) when the Body is non-nil. requiresHTTP1 reports whether this request requires being sent on
an HTTP/1 connection.(*Request) wantsClose() bool(*Request) wantsHttp10KeepAlive() bool extraHeaders may be nil
waitForContinue may be nil
always closes body
func NewRequest(method, url string, body io.Reader) (*Request, error)
func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error)
func ReadRequest(b *bufio.Reader) (*Request, error)
func (*Request).Clone(ctx context.Context) *Request
func (*Request).WithContext(ctx context.Context) *Request
func http2shouldRetryRequest(req *Request, err error) (*Request, error)
func readRequest(b *bufio.Reader) (req *Request, err error)
func rewindBody(req *Request) (rewound *Request, err error)
func setupRewindBody(req *Request) *Request
func NotFound(w ResponseWriter, r *Request)
func ProxyFromEnvironment(req *Request) (*url.URL, error)
func ReadResponse(r *bufio.Reader, req *Request) (*Response, error)
func Redirect(w ResponseWriter, r *Request, url string, code int)
func ServeContent(w ResponseWriter, req *Request, name string, modtime time.Time, content io.ReadSeeker)
func ServeFile(w ResponseWriter, r *Request, name string)
func (*Client).Do(req *Request) (*Response, error)
func Handler.ServeHTTP(ResponseWriter, *Request)
func HandlerFunc.ServeHTTP(w ResponseWriter, r *Request)
func RoundTripper.RoundTrip(*Request) (*Response, error)
func (*ServeMux).Handler(r *Request) (h Handler, pattern string)
func (*ServeMux).ServeHTTP(w ResponseWriter, r *Request)
func (*Transport).CancelRequest(req *Request)
func (*Transport).RoundTrip(req *Request) (*Response, error)
func go.uber.org/zap.AtomicLevel.ServeHTTP(w ResponseWriter, r *Request)
func nhooyr.io/websocket.Accept(w ResponseWriter, r *Request, opts *websocket.AcceptOptions) (*websocket.Conn, error)
func checkIfMatch(w ResponseWriter, r *Request) condResult
func checkIfModifiedSince(r *Request, modtime time.Time) condResult
func checkIfNoneMatch(w ResponseWriter, r *Request) condResult
func checkIfRange(w ResponseWriter, r *Request, modtime time.Time) condResult
func checkIfUnmodifiedSince(r *Request, modtime time.Time) condResult
func checkPreconditions(w ResponseWriter, r *Request, modtime time.Time) (done bool, rangeHeader string)
func defaultCheckRedirect(req *Request, via []*Request) error
func defaultCheckRedirect(req *Request, via []*Request) error
func dirList(w ResponseWriter, r *Request, f File)
func http1ServerSupportsRequest(req *Request) bool
func http2actualContentLength(req *Request) int64
func http2checkConnHeaders(req *Request) error
func http2commaSeparatedTrailers(req *Request) (string, error)
func http2handleHeaderListTooLong(w ResponseWriter, r *Request)
func http2isConnectionCloseRequest(req *Request) bool
func http2shouldRetryDial(call *http2dialCall, req *Request) bool
func http2shouldRetryRequest(req *Request, err error) (*Request, error)
func http2traceGetConn(req *Request, hostPort string)
func http2traceGotConn(req *Request, cc *http2ClientConn, reused bool)
func knownRoundTripperImpl(rt RoundTripper, req *Request) bool
func localRedirect(w ResponseWriter, r *Request, newPath string)
func logf(r *Request, format string, args ...any)
func parsePostForm(r *Request) (vs url.Values, err error)
func redirectBehavior(reqMethod string, resp *Response, ireq *Request) (redirectMethod string, shouldRedirect, includeBody bool)
func rewindBody(req *Request) (rewound *Request, err error)
func send(ireq *Request, rt RoundTripper, deadline time.Time) (resp *Response, didTimeout func() bool, err error)
func serveContent(w ResponseWriter, r *Request, name string, modtime time.Time, sizeFunc func() (int64, error), content io.ReadSeeker)
func serveFile(w ResponseWriter, r *Request, fs FileSystem, name string, redirect bool)
func setRequestCancel(req *Request, rt RoundTripper, deadline time.Time) (stopTimer func(), didTimeout func() bool)
func setupRewindBody(req *Request) *Request
func (*Client).checkRedirect(req *Request, via []*Request) error
func (*Client).checkRedirect(req *Request, via []*Request) error
func (*Client).do(req *Request) (retres *Response, reterr error)
func (*Client).makeHeadersCopier(ireq *Request) func(*Request)
func (*Client).send(req *Request, deadline time.Time) (resp *Response, didTimeout func() bool, err error)
func (*Transport).alternateRoundTripper(req *Request) RoundTripper
func (*Transport).roundTrip(req *Request) (*Response, error)
func (*Transport).useRegisteredProtocol(req *Request) bool
func go.uber.org/zap.decodePutRequest(contentType string, r *Request) (zapcore.Level, error)
func go.uber.org/zap.decodePutURL(r *Request) (zapcore.Level, error)
func go.uber.org/zap.AtomicLevel.serveHTTP(w ResponseWriter, r *Request) error
func nhooyr.io/websocket.accept(w ResponseWriter, r *Request, opts *websocket.AcceptOptions) (_ *websocket.Conn, err error)
func nhooyr.io/websocket.authenticateOrigin(r *Request, originHosts []string) error
func nhooyr.io/websocket.selectSubprotocol(r *Request, subprotocols []string) string
func nhooyr.io/websocket.verifyClientRequest(w ResponseWriter, r *Request) (errCode int, _ error)
Response represents the response from an HTTP request.
The Client and Transport return Responses from servers once
the response headers have been received. The response body
is streamed on demand as the Body field is read. 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. 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. 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. 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). // e.g. "HTTP/1.0" // e.g. 1 // e.g. 0 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. // e.g. "200 OK" // e.g. 200 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. 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. Contains transfer encodings from outer-most to inner-most. Value is
nil, means that "identity" encoding is used. 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. Cookies parses and returns the cookies set in the Set-Cookie headers. Location returns the URL of the response's "Location" header,
if present. Relative redirects are resolved relative to
the Response's Request. ErrNoLocation is returned if no
Location header is present. ProtoAtLeast reports whether the HTTP protocol used
in the response is at least major.minor. Write writes r to w in the HTTP/1.x server response format,
including the status line, headers, body, and optional trailer.
This method consults the following fields of the response r:
StatusCode
ProtoMajor
ProtoMinor
Request.Method
TransferEncoding
Trailer
Body
ContentLength
Header, values for non-canonical keys will have unpredictable behavior
The Response Body is closed after it is sent. bodyIsWritable reports whether the Body supports writing. The
Transport returns Writable bodies for 101 Switching Protocols
responses.
The Transport uses this method to determine whether a persistent
connection is done being managed from its perspective. Once we
return a writable response body to a user, the net/http package is
done managing that connection.(*Response) closeBody() isProtocolSwitch reports whether the response code and header
indicate a successful protocol upgrade response.
func Get(url string) (resp *Response, err error)
func Head(url string) (resp *Response, err error)
func Post(url, contentType string, body io.Reader) (resp *Response, err error)
func PostForm(url string, data url.Values) (resp *Response, err error)
func ReadResponse(r *bufio.Reader, req *Request) (*Response, error)
func (*Client).Do(req *Request) (*Response, error)
func (*Client).Get(url string) (resp *Response, err error)
func (*Client).Head(url string) (resp *Response, err error)
func (*Client).Post(url, contentType string, body io.Reader) (resp *Response, err error)
func (*Client).PostForm(url string, data url.Values) (resp *Response, err error)
func RoundTripper.RoundTrip(*Request) (*Response, error)
func (*Transport).RoundTrip(req *Request) (*Response, error)
func nhooyr.io/websocket.Dial(ctx context.Context, u string, opts *websocket.DialOptions) (*websocket.Conn, *Response, error)
func newPopulateResponseWriter() (*populateResponse, <-chan *Response)
func send(ireq *Request, rt RoundTripper, deadline time.Time) (resp *Response, didTimeout func() bool, err error)
func (*Client).do(req *Request) (retres *Response, reterr error)
func (*Client).send(req *Request, deadline time.Time) (resp *Response, didTimeout func() bool, err error)
func (*Transport).roundTrip(req *Request) (*Response, error)
func nhooyr.io/websocket.dial(ctx context.Context, urls string, opts *websocket.DialOptions, rand io.Reader) (_ *websocket.Conn, _ *Response, err error)
func nhooyr.io/websocket.handshakeRequest(ctx context.Context, urls string, opts *websocket.DialOptions, copts *websocket.compressionOptions, secWebSocketKey string) (*Response, error)
func redirectBehavior(reqMethod string, resp *Response, ireq *Request) (redirectMethod string, shouldRedirect, includeBody bool)
func nhooyr.io/websocket.verifyServerResponse(opts *websocket.DialOptions, copts *websocket.compressionOptions, secWebSocketKey string, resp *Response) (*websocket.compressionOptions, error)
func nhooyr.io/websocket.verifySubprotocol(subprotos []string, resp *Response) error
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.rwResponseWriter EnableFullDuplex indicates that the request handler will interleave reads from Request.Body
with writes to the ResponseWriter.
For HTTP/1 requests, the Go HTTP server by default consumes any unread portion of
the request body before beginning to write the response, preventing handlers from
concurrently reading from the request and writing the response.
Calling EnableFullDuplex disables this behavior and permits handlers to continue to read
from the request while concurrently writing the response.
For HTTP/2 requests, the Go HTTP server always permits concurrent reads and responses. Flush flushes buffered data to the client. Hijack lets the caller take over the connection.
See the Hijacker interface for details. 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. 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.
*ResponseController : Hijacker
func NewResponseController(rw ResponseWriter) *ResponseController
A ResponseWriter interface is used by an HTTP handler to
construct an HTTP response.
A ResponseWriter may not be used after the Handler.ServeHTTP method
has returned. Header returns the header map that will be sent by
WriteHeader. The Header map also is the mechanism with which
Handlers can set HTTP trailers.
Changing the header map after a call to WriteHeader (or
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 Write,
is to prefix the Header map keys with the TrailerPrefix
constant value. See TrailerPrefix.
To suppress automatic response headers (such as "Date"), set
their value to nil. Write writes the data to the connection as part of an HTTP reply.
If 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. 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.
*http2responseWriter
*populateResponse
*response
*timeoutWriter
ResponseWriter : internal/bisect.Writer
ResponseWriter : io.Writer
ResponseWriter : crypto/tls.transcriptHash
func Error(w ResponseWriter, error string, code int)
func MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser
func NewResponseController(rw ResponseWriter) *ResponseController
func NotFound(w ResponseWriter, r *Request)
func Redirect(w ResponseWriter, r *Request, url string, code int)
func ServeContent(w ResponseWriter, req *Request, name string, modtime time.Time, content io.ReadSeeker)
func ServeFile(w ResponseWriter, r *Request, name string)
func SetCookie(w ResponseWriter, cookie *Cookie)
func Handler.ServeHTTP(ResponseWriter, *Request)
func HandlerFunc.ServeHTTP(w ResponseWriter, r *Request)
func (*ServeMux).ServeHTTP(w ResponseWriter, r *Request)
func go.uber.org/zap.AtomicLevel.ServeHTTP(w ResponseWriter, r *Request)
func nhooyr.io/websocket.Accept(w ResponseWriter, r *Request, opts *websocket.AcceptOptions) (*websocket.Conn, error)
func checkIfMatch(w ResponseWriter, r *Request) condResult
func checkIfNoneMatch(w ResponseWriter, r *Request) condResult
func checkIfRange(w ResponseWriter, r *Request, modtime time.Time) condResult
func checkPreconditions(w ResponseWriter, r *Request, modtime time.Time) (done bool, rangeHeader string)
func dirList(w ResponseWriter, r *Request, f File)
func http2handleHeaderListTooLong(w ResponseWriter, r *Request)
func localRedirect(w ResponseWriter, r *Request, newPath string)
func serveContent(w ResponseWriter, r *Request, name string, modtime time.Time, sizeFunc func() (int64, error), content io.ReadSeeker)
func serveFile(w ResponseWriter, r *Request, fs FileSystem, name string, redirect bool)
func setLastModified(w ResponseWriter, modtime time.Time)
func writeNotModified(w ResponseWriter)
func go.uber.org/zap.AtomicLevel.serveHTTP(w ResponseWriter, r *Request) error
func nhooyr.io/websocket.accept(w ResponseWriter, r *Request, opts *websocket.AcceptOptions) (_ *websocket.Conn, err error)
func nhooyr.io/websocket.verifyClientRequest(w ResponseWriter, r *Request) (errCode int, _ error)
RoundTripper is an interface representing the ability to execute a
single HTTP transaction, obtaining the Response for a given Request.
A RoundTripper must be safe for concurrent use by multiple
goroutines. 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.
*TransportfileTransport
*http2ClientConnhttp2erringRoundTripperhttp2noDialH2RoundTripper
*http2Transport
func NewFileTransport(fs FileSystem) RoundTripper
func (*Client).transport() RoundTripper
func (*Transport).alternateRoundTripper(req *Request) RoundTripper
func (*Transport).RegisterProtocol(scheme string, rt RoundTripper)
func knownRoundTripperImpl(rt RoundTripper, req *Request) bool
func send(ireq *Request, rt RoundTripper, deadline time.Time) (resp *Response, didTimeout func() bool, err error)
func setRequestCancel(req *Request, rt RoundTripper, deadline time.Time) (stopTimer func(), didTimeout func() bool)
var DefaultTransport
SameSite allows a server to define a cookie attribute making it impossible for
the browser to send this cookie along with cross-site requests. The main
goal is to mitigate the risk of cross-origin information leakage, and provide
some protection against cross-site request forgery attacks.
See https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00 for details.
const SameSiteDefaultMode
const SameSiteLaxMode
const SameSiteNoneMode
const SameSiteStrictMode
ServeMux is an HTTP request multiplexer.
It matches the URL of each incoming request against a list of registered
patterns and calls the handler for the pattern that
most closely matches the URL.
Patterns name fixed, rooted paths, like "/favicon.ico",
or rooted subtrees, like "/images/" (note the trailing slash).
Longer patterns take precedence over shorter ones, so that
if there are handlers registered for both "/images/"
and "/images/thumbnails/", the latter handler will be
called for paths beginning with "/images/thumbnails/" and the
former will receive requests for any other paths in the
"/images/" subtree.
Note that since a pattern ending in a slash names a rooted subtree,
the pattern "/" matches all paths not matched by other registered
patterns, not just the URL with Path == "/".
If a subtree has been registered and a request is received naming the
subtree root without its trailing slash, ServeMux redirects that
request to the subtree root (adding the trailing slash). This behavior can
be overridden with a separate registration for the path without
the trailing slash. For example, registering "/images/" causes ServeMux
to redirect a request for "/images" to "/images/", unless "/images" has
been registered separately.
Patterns may optionally begin with a host name, restricting matches to
URLs on that host only. Host-specific patterns take precedence over
general patterns, so that a handler might register for the two patterns
"/codesearch" and "codesearch.google.com/" without also taking over
requests for "http://www.google.com/".
ServeMux also takes care of sanitizing the URL request path and the Host
header, stripping the port number and redirecting any request containing . or
.. elements or repeated slashes to an equivalent, cleaner URL. // slice of entries sorted from longest to shortest. // whether any patterns contain hostnamesmmap[string]muxEntrymusync.RWMutex Handle registers the handler for the given pattern.
If a handler already exists for pattern, Handle panics. HandleFunc registers the handler function for the given pattern. Handler returns the handler to use for the given request,
consulting r.Method, r.Host, and r.URL.Path. It always returns
a non-nil handler. If the path is not in its canonical form, the
handler will be an internally-generated handler that redirects
to the canonical path. If the host contains a port, it is ignored
when matching handlers.
The path and host are used unchanged for CONNECT requests.
Handler also returns the registered pattern that matches the
request or, in the case of internally-generated redirects,
the pattern that will match after following the redirect.
If there is no registered handler that applies to the request,
Handler returns a “page not found” handler and an empty pattern. ServeHTTP dispatches the request to the handler whose
pattern most closely matches the request URL. handler is the main implementation of Handler.
The path is known to be in canonical form, except for CONNECT methods. Find a handler on a handler map given a path string.
Most-specific (longest) pattern wins. redirectToPathSlash determines if the given path needs appending "/" to it.
This occurs when a handler for path + "/" was already registered, but
not for path itself. If the path needs appending to, it creates a new
URL, setting the path to u.Path + "/" and returning true to indicate so. shouldRedirectRLocked reports whether the given path and host should be redirected to
path+"/". This should happen if a handler is registered for path+"/" but
not path -- see comments at ServeMux.
*ServeMux : Handler
func NewServeMux() *ServeMux
var DefaultServeMux *ServeMux
var defaultServeMux
A Server defines parameters for running an HTTP server.
The zero value for Server is a valid configuration. 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 in RFC 6335 and assigned by IANA.
See net.Dial for details of the address format. 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. 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. ConnState specifies an optional callback function that is
called when a client connection changes state. See the
ConnState type and associated constants for details. DisableGeneralOptionsHandler, if true, passes "OPTIONS *" requests to the Handler,
otherwise responds with 200 OK and Content-Length: 0. 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. // handler to invoke, http.DefaultServeMux if nil IdleTimeout is the maximum amount of time to wait for the
next request when keep-alives are enabled. If IdleTimeout
is zero, the value of ReadTimeout is used. If both are
zero, there is no timeout. 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. 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 ReadHeaderTimeout
is zero, the value of ReadTimeout is used. If both are
zero, there is no timeout. 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. 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. 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. 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.activeConnmap[*conn]struct{}disableKeepAlivesatomic.Bool // true when server is in shutdownlistenerGroupsync.WaitGrouplistenersmap[*net.Listener]struct{}musync.Mutex // result of http2.ConfigureServer if used // guards setupHTTP2_* initonShutdown[]func() Close immediately closes all active net.Listeners and any
connections in state StateNew, StateActive, or StateIdle. For a
graceful shutdown, use Shutdown.
Close does not attempt to close (and does not even know about)
any hijacked connections, such as WebSockets.
Close returns any error returned from closing the Server's
underlying Listener(s). ListenAndServe listens on the TCP network address srv.Addr and then
calls Serve to handle requests on incoming connections.
Accepted connections are configured to enable TCP keep-alives.
If srv.Addr is blank, ":http" is used.
ListenAndServe always returns a non-nil error. After Shutdown or Close,
the returned error is ErrServerClosed. ListenAndServeTLS listens on the TCP network address srv.Addr and
then calls ServeTLS to handle requests on incoming TLS connections.
Accepted connections are configured to enable TCP keep-alives.
Filenames containing a certificate and matching private key for the
server must be provided if neither the Server's TLSConfig.Certificates
nor TLSConfig.GetCertificate are populated. If the certificate is
signed by a certificate authority, the certFile should be the
concatenation of the server's certificate, any intermediates, and
the CA's certificate.
If srv.Addr is blank, ":https" is used.
ListenAndServeTLS always returns a non-nil error. After Shutdown or
Close, the returned error is ErrServerClosed. RegisterOnShutdown registers a function to call on Shutdown.
This can be used to gracefully shutdown connections that have
undergone ALPN protocol upgrade or that have been hijacked.
This function should start protocol-specific graceful shutdown,
but should not wait for shutdown to complete. Serve accepts incoming connections on the Listener l, creating a
new service goroutine for each. The service goroutines read requests and
then call srv.Handler to reply to them.
HTTP/2 support is only enabled if the Listener returns *tls.Conn
connections and they were configured with "h2" in the TLS
Config.NextProtos.
Serve always returns a non-nil error and closes l.
After Shutdown or Close, the returned error is ErrServerClosed. ServeTLS accepts incoming connections on the Listener l, creating a
new service goroutine for each. The service goroutines perform TLS
setup and then read requests, calling srv.Handler to reply to them.
Files containing a certificate and matching private key for the
server must be provided if neither the Server's
TLSConfig.Certificates nor TLSConfig.GetCertificate are populated.
If the certificate is signed by a certificate authority, the
certFile should be the concatenation of the server's certificate,
any intermediates, and the CA's certificate.
ServeTLS always returns a non-nil error. After Shutdown or Close, the
returned error is ErrServerClosed. SetKeepAlivesEnabled controls whether HTTP keep-alives are enabled.
By default, keep-alives are always enabled. Only very
resource-constrained environments or servers in the process of
shutting down should disable them. Shutdown gracefully shuts down the server without interrupting any
active connections. Shutdown works by first closing all open
listeners, then closing all idle connections, and then waiting
indefinitely for connections to return to idle and then shut down.
If the provided context expires before the shutdown is complete,
Shutdown returns the context's error, otherwise it returns any
error returned from closing the Server's underlying Listener(s).
When Shutdown is called, Serve, ListenAndServe, and
ListenAndServeTLS immediately return ErrServerClosed. Make sure the
program doesn't exit and waits instead for Shutdown to return.
Shutdown does not attempt to close nor wait for hijacked
connections such as WebSockets. The caller of Shutdown should
separately notify such long-lived connections of shutdown and wait
for them to close, if desired. See RegisterOnShutdown for a way to
register shutdown notification functions.
Once Shutdown has been called on a server, it may not be reused;
future calls to methods such as Serve will return ErrServerClosed. closeIdleConns closes all idle connections and reports whether the
server is quiescent.(*Server) closeListenersLocked() error(*Server) doKeepAlives() bool(*Server) idleTimeout() time.Duration(*Server) initialReadLimitSize() int64(*Server) logf(format string, args ...any)(*Server) maxHeaderBytes() int Create new connection from rwc. onceSetNextProtoDefaults configures HTTP/2, if the user hasn't
configured otherwise. (by setting srv.TLSNextProto non-nil)
It must only be called via srv.nextProtoOnce (use srv.setupHTTP2_*).(*Server) onceSetNextProtoDefaults_Serve()(*Server) readHeaderTimeout() time.Duration setupHTTP2_Serve is called from (*Server).Serve and conditionally
configures HTTP/2 on srv using a more conservative policy than
setupHTTP2_ServeTLS because Serve is called after tls.Listen,
and may be called concurrently. See shouldConfigureHTTP2ForServe.
The tests named TestTransportAutomaticHTTP2* and
TestConcurrentServerServe in server_test.go demonstrate some
of the supported use cases and motivations. setupHTTP2_ServeTLS conditionally configures HTTP/2 on
srv and reports whether there was an error setting it up. If it is
not configured for policy reasons, nil is returned. shouldConfigureHTTP2ForServe reports whether Server.Serve should configure
automatic HTTP/2. (which sets up the srv.TLSNextProto map)(*Server) shuttingDown() bool tlsHandshakeTimeout returns the time limit permitted for the TLS
handshake, or zero for unlimited.
It returns the minimum of any positive ReadHeaderTimeout,
ReadTimeout, or WriteTimeout.(*Server) trackConn(c *conn, add bool) trackListener adds or removes a net.Listener to the set of tracked
listeners.
We store a pointer to interface in the map set, in case the
net.Listener is not comparable. This is safe because we only call
trackListener via Serve and can track+defer untrack the same
pointer to local variable there. We never need to compare a
Listener from another caller.
It reports whether the server is still up (not Shutdown or Closed).
*Server : io.Closer
func http2ConfigureServer(s *Server, conf *http2Server) error
func http2h1ServerKeepAlivesDisabled(hs *Server) bool
Transport is an implementation of RoundTripper that supports HTTP,
HTTPS, and HTTP proxies (for either HTTP or HTTPS with CONNECT).
By default, Transport caches connections for future re-use.
This may leave many open connections when accessing many hosts.
This behavior can be managed using Transport's CloseIdleConnections method
and the MaxIdleConnsPerHost and DisableKeepAlives fields.
Transports should be reused instead of created as needed.
Transports are safe for concurrent use by multiple goroutines.
A Transport is a low-level primitive for making HTTP and HTTPS requests.
For high-level functionality, such as cookies and redirects, see Client.
Transport uses HTTP/1.1 for HTTP URLs and either HTTP/1.1 or HTTP/2
for HTTPS URLs, depending on whether the server supports HTTP/2,
and how the Transport is configured. The DefaultTransport supports HTTP/2.
To explicitly enable HTTP/2 on a transport, use golang.org/x/net/http2
and call ConfigureTransport. See the package docs for more about HTTP/2.
Responses with status codes in the 1xx range are either handled
automatically (100 expect-continue) or ignored. The one
exception is HTTP status code 101 (Switching Protocols), which is
considered a terminal status and returned by RoundTrip. To see the
ignored 1xx responses, use the httptrace trace package's
ClientTrace.Got1xxResponse.
Transport only retries a request upon encountering a network error
if the connection has been already been used successfully and if the
request is idempotent and either has no body or has its Request.GetBody
defined. HTTP requests are considered idempotent if they have HTTP methods
GET, HEAD, OPTIONS, or TRACE; or if their Header map contains an
"Idempotency-Key" or "X-Idempotency-Key" entry. If the idempotency key
value is a zero-length slice, the request is treated as idempotent but the
header is not sent on the wire. 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. 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. 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. 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. 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. 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. 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. 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. 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. IdleConnTimeout is the maximum amount of time an idle
(keep-alive) connection will remain idle before closing
itself.
Zero means no limit. 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. MaxIdleConns controls the maximum number of idle (keep-alive)
connections across all hosts. Zero means no limit. MaxIdleConnsPerHost, if non-zero, controls the maximum idle
(keep-alive) connections to keep per-host. If zero,
DefaultMaxIdleConnsPerHost is used. MaxResponseHeaderBytes specifies a limit on how many
response bytes are allowed in the server's response
header.
Zero means to use a default limit. 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. 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", and "socks5" are supported. If the scheme is empty,
"http" is assumed.
If Proxy is nil or returns a nil *URL, no proxy is used. ProxyConnectHeader optionally specifies headers to send to
proxies during CONNECT requests.
To set the header dynamically, see GetProxyConnectHeader. ReadBufferSize specifies the size of the read buffer used
when reading from the transport.
If zero, a default (currently 4KB) is used. 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. 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. TLSHandshakeTimeout specifies the maximum amount of time to
wait for a TLS handshake. Zero means no timeout. TLSNextProto specifies how the Transport switches to an
alternate protocol (such as HTTP/2) after a TLS ALPN
protocol negotiation. If Transport dials an 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. WriteBufferSize specifies the size of the write buffer used
when writing to the transport.
If zero, a default (currently 4KB) is used. // guards changing altProto only // of nil or map[string]RoundTripper, key is URI scheme // user has requested to close all idle connsconnsPerHostmap[connectMethodKey]intconnsPerHostMusync.Mutex // waiting getConns // non-nil if http2 wired up // most recently used at end // waiting getConnsidleLRUconnLRUidleMusync.Mutex nextProtoOnce guards initialization of TLSNextProto and
h2transport (via onceSetNextProtoDefaults)reqCancelermap[cancelKey]func(error)reqMusync.Mutex // whether TLSNextProto was nil when the Once fired CancelRequest cancels an in-flight request by closing its connection.
CancelRequest should only be called after RoundTrip has returned.
Deprecated: Use Request.WithContext to create a request with a
cancelable context instead. CancelRequest cannot cancel HTTP/2
requests. Clone returns a deep copy of t's exported fields. CloseIdleConnections closes any connections which were previously
connected from previous requests but are now sitting idle in
a "keep-alive" state. It does not interrupt any connections currently
in use. RegisterProtocol registers a new protocol with scheme.
The Transport will pass requests using the given scheme to rt.
It is rt's responsibility to simulate HTTP request semantics.
RegisterProtocol can be used by other packages to provide
implementations of protocol schemes like "ftp" or "file".
If rt.RoundTrip returns ErrSkipAltProtocol, the Transport will
handle the RoundTrip itself for that one request, as if the
protocol were not registered. RoundTrip implements the RoundTripper interface.
For higher-level HTTP client support (such as handling of cookies
and redirects), see Get, Post, and the Client type.
Like the RoundTripper interface, the error types returned
by RoundTrip are unspecified. alternateRoundTripper returns the alternate RoundTripper to use
for this request if the Request's URL scheme requires one,
or nil for the normal case of using the Transport. Cancel an in-flight request, recording the error value.
Returns whether the request was canceled.(*Transport) connectMethodForRequest(treq *transportRequest) (cm connectMethod, err error)(*Transport) customDialTLS(ctx context.Context, network, addr string) (conn net.Conn, err error) decConnsPerHost decrements the per-host connection count for key,
which may in turn give a different waiting goroutine permission to dial.(*Transport) dial(ctx context.Context, network, addr string) (net.Conn, error)(*Transport) dialConn(ctx context.Context, cm connectMethod) (pconn *persistConn, err error) dialConnFor dials on behalf of w and delivers the result to w.
dialConnFor has received permission to dial w.cm and is counted in t.connCount[w.cm.key()].
If the dial is canceled or unsuccessful, dialConnFor decrements t.connCount[w.cm.key()]. getConn dials and creates a new persistConn to the target as
specified in the connectMethod. This includes doing a proxy CONNECT
and/or setting up TLS. If this doesn't return an error, the persistConn
is ready to write requests to.(*Transport) hasCustomTLSDialer() bool(*Transport) maxIdleConnsPerHost() int onceSetNextProtoDefaults initializes TLSNextProto.
It must be called via t.nextProtoOnce.Do.(*Transport) putOrCloseIdleConn(pconn *persistConn) queueForDial queues w to wait for permission to begin dialing.
Once w receives permission to dial, it will do so in a separate goroutine. queueForIdleConn queues w to receive the next idle connection for w.cm.
As an optimization hint to the caller, queueForIdleConn reports whether
it successfully delivered an already-idle connection.(*Transport) readBufferSize() int removeIdleConn marks pconn as dead. t.idleMu must be held. replaceReqCanceler replaces an existing cancel function. If there is no cancel function
for the request, we don't set the function and return false.
Since CancelRequest will clear the canceler, we can use the return value to detect if
the request was canceled since the last setReqCancel call. roundTrip implements a RoundTripper over HTTP.(*Transport) setReqCanceler(key cancelKey, fn func(error)) tryPutIdleConn adds pconn to the list of idle persistent connections awaiting
a new request.
If pconn is no longer needed or not in a good state, tryPutIdleConn returns
an error explaining why it wasn't registered.
tryPutIdleConn does not close pconn. Use putOrCloseIdleConn instead for that. useRegisteredProtocol reports whether an alternate protocol (as registered
with Transport.RegisterProtocol) should be respected for this request.(*Transport) writeBufferSize() int
*Transport : RoundTripper
*Transport : h2Transport
func (*Transport).Clone() *Transport
func http2ConfigureTransport(t1 *Transport) error
func http2ConfigureTransports(t1 *Transport) (*http2Transport, error)
func http2configureTransports(t1 *Transport) (*http2Transport, error)
func http2registerHTTPSProtocol(t *Transport, rt http2noDialH2RoundTripper) (err error)
body turns a Reader into a ReadCloser.
Close ensures that the body has been fully read
and then reads the trailer if necessary.closedbool // is the connection to be closed after reading body? // whether Close should stop early // Close called and we didn't read to the end of src // non-nil (Response or Request) value means read trailer // guards following, and calls to Read and Close // if non-nil, func to call when EOF is Read // underlying wire-format reader for the trailersawEOFboolsrcio.Reader(*body) Close() error(*body) Read(p []byte) (n int, err error) bodyRemains reports whether future Read calls might
yield data.(*body) didEarlyClose() bool Must hold b.mu.(*body) readTrailer() error(*body) registerOnHitEOF(fn func()) unreadDataSizeLocked returns the number of bytes of unread input.
It returns -1 if unknown.
b.mu must be held.
*body : io.Closer
*body : io.ReadCloser
*body : io.Reader
bodyEOFSignal is used by the HTTP/1 transport when reading response
bodies to make sure we see the end of a response body before
proceeding and reading on the connection again.
It wraps a ReadCloser but runs fn (if non-nil) at most
once, right before its final (error-producing) Read or Close call
returns. fn should return the new error to return from Read or Close.
If earlyCloseFn is non-nil and Close is called before io.EOF is
seen, earlyCloseFn is called instead of fn, and its return value is
the return value from Close.bodyio.ReadCloser // whether Close has been called // optional alt Close func used if io.EOF not seen // err will be nil on Read io.EOF // guards following 4 fields // sticky Read error(*bodyEOFSignal) Close() error(*bodyEOFSignal) Read(p []byte) (n int, err error) caller must hold es.mu.
*bodyEOFSignal : io.Closer
*bodyEOFSignal : io.ReadCloser
*bodyEOFSignal : io.Reader
bodyLocked is an io.Reader reading from a *body when its mutex is
already held.b*body( bodyLocked) Read(p []byte) (n int, err error)
bodyLocked : io.Reader
bufioFlushWriter is an io.Writer wrapper that flushes all writes
on its wrapped writer if it's a *bufio.Writer.wio.Writer( bufioFlushWriter) Write(p []byte) (n int, err error)
bufioFlushWriter : internal/bisect.Writer
bufioFlushWriter : io.Writer
bufioFlushWriter : crypto/tls.transcriptHash
cancelTimerBody is an io.ReadCloser that wraps rc with two features:
1. On Read error or close, the stop func is called.
2. On Read failure, if reqDidTimeout is true, the error is wrapped and
marked as net.Error that hit its timeout.rcio.ReadCloserreqDidTimeoutfunc() bool // stops the time.Timer waiting to cancel the request(*cancelTimerBody) Close() error(*cancelTimerBody) Read(p []byte) (n int, err error)
*cancelTimerBody : io.Closer
*cancelTimerBody : io.ReadCloser
*cancelTimerBody : io.Reader
checkConnErrorWriter writes to c.rwc and records any write errors to c.werr.
It only contains one field (and a pointer field at that), so it
fits in an interface value without an extra allocation.c*conn( checkConnErrorWriter) Write(p []byte) (n int, err error)
checkConnErrorWriter : internal/bisect.Writer
checkConnErrorWriter : io.Writer
checkConnErrorWriter : crypto/tls.transcriptHash
chunkWriter writes to a response's conn buffer, and is the writer
wrapped by the response.w buffered writer.
chunkWriter also is responsible for finalizing the Header, including
conditionally setting the Content-Type and setting a Content-Length
in cases where the handler's final output is smaller than the buffer
size. It also conditionally adds chunk headers, when in chunking mode.
See the comment above (*response).Write for the entire write flow. set by the writeHeader method: // using chunked transfer encoding for reply body header is either nil or a deep clone of res.handlerHeader
at the time of res.writeHeader, if res.writeHeader is
called and extra buffering is being done to calculate
Content-Type and/or Content-Length.res*response wroteHeader tells whether the header's been written to "the
wire" (or rather: w.conn.buf). this is unlike
(*response).wroteHeader, which tells only whether it was
logically written.(*chunkWriter) Write(p []byte) (n int, err error)(*chunkWriter) close()(*chunkWriter) flush() error writeHeader finalizes the header sent to the client and writes it
to cw.res.conn.bufw.
p is not written by writeHeader, but is the first chunk of the body
that will be written. It is sniffed for a Content-Type if none is
set explicitly. It's also used to set the Content-Length, if the
total body size was small and the handler has already finished
running.
*chunkWriter : internal/bisect.Writer
*chunkWriter : io.Writer
*chunkWriter : crypto/tls.transcriptHash
A conn represents the server side of an HTTP connection. bufr reads from r. bufw writes to checkConnErrorWriter{c}, which populates werr on error. cancelCtx cancels the connection-level context. // (which has a Request in it) // packed (unixtime<<8|uint8(ConnState)) hijackedv is whether this connection has been hijacked
by a Handler with the Hijacker interface.
It is guarded by mu. lastMethod is the method of the most recent request
on this connection, if any. mu guards hijackedv r is bufr's read source. It's a wrapper around rwc that provides
io.LimitedReader-style limiting (while reading request headers)
and functionality to support CloseNotifier. See *connReader docs. remoteAddr is rwc.RemoteAddr().String(). It is not populated synchronously
inside the Listener's Accept goroutine, as some implementations block.
It is populated immediately inside the (*conn).serve goroutine.
This is the value of a Handler's (*Request).RemoteAddr. rwc is the underlying network connection.
This is never wrapped by other types and is the value given out
to CloseNotifier callers. It is usually of type *net.TCPConn or
*tls.Conn. server is the server on which the connection arrived.
Immutable; never nil. tlsState is the TLS connection state when using TLS.
nil means not TLS. werr is set to the first write error to rwc.
It is set via checkConnErrorWriter{w}, where bufw writes. Close the connection. closeWriteAndWait flushes any outstanding data and sends a FIN packet (if
client is connected via TCP), signaling that we're done. We then
pause for a bit, hoping the client processes it before any
subsequent RST.
See https://golang.org/issue/3595(*conn) finalFlush()(*conn) getState() (state ConnState, unixSec int64) c.mu must be held.(*conn) hijacked() bool Read next request from connection. Serve a new connection.(*conn) setState(nc net.Conn, state ConnState, runHook bool)
func (*Server).newConn(rwc net.Conn) *conn
func (*Server).trackConn(c *conn, add bool)
connectMethod is the map key (in its String form) for keeping persistent
TCP connections alive for subsequent HTTP requests.
A connect method may be of the following types:
connectMethod.key().String() Description
------------------------------ -------------------------
|http|foo.com http directly to server, no proxy
|https|foo.com https directly to server, no proxy
|https,h1|foo.com https directly to server w/o HTTP/2, no proxy
http://proxy.com|https|foo.com http to proxy, then CONNECT to foo.com
http://proxy.com|http http to proxy, http to anywhere after that
socks5://proxy.com|http|foo.com socks5 to proxy, then http to foo.com
socks5://proxy.com|https|foo.com socks5 to proxy, then https to foo.com
https://proxy.com|https|foo.com https to proxy, then CONNECT to foo.com
https://proxy.com|http https to proxy, http to anywhere after that // whether to disable HTTP/2 and force HTTP/1 // nil for no proxy, else full proxy URL If proxyURL specifies an http or https proxy, and targetScheme is http (not https),
then targetAddr is not included in the connect method key, because the socket can
be reused for different targetAddr values. // "http" or "https" addr returns the first hop "host:port" to which we need to TCP connect.(*connectMethod) key() connectMethodKey proxyAuth returns the Proxy-Authorization header to set
on requests, if applicable. scheme returns the first hop scheme: http, https, or socks5 tlsHost returns the host name to match against the peer's
TLS certificate.
func (*Transport).connectMethodForRequest(treq *transportRequest) (cm connectMethod, err error)
func (*Transport).dialConn(ctx context.Context, cm connectMethod) (pconn *persistConn, err error)
func (*Transport).getConn(treq *transportRequest, cm connectMethod) (pc *persistConn, err error)
// list.Element.Value type is of *persistConnmmap[*persistConn]*list.Element add adds pc to the head of the linked list. len returns the number of items in the cache. remove removes pc from cl.(*connLRU) removeOldest() *persistConn
connReader is the io.Reader wrapper used by *conn. It combines a
selectively-activated io.LimitedReader (to bound request header
read sizes) with support for selectively keeping an io.Reader.Read
call blocked in a background goroutine to wait for activity and
trigger a CloseNotifier channel. // set true before conn.rwc deadline is set to pastbyteBuf[1]bytecond*sync.Condconn*connhasByteboolinReadbool // guards following // bytes remaining(*connReader) Read(p []byte) (n int, err error)(*connReader) abortPendingRead()(*connReader) backgroundRead() may be called from multiple goroutines. handleReadError is called whenever a Read from the client returns a
non-nil error.
The provided non-nil err is almost always io.EOF or a "use of
closed network connection". In any case, the error is not
particularly interesting, except perhaps for debugging during
development. Any error means the connection is dead and we should
down its context.
It may be called from multiple goroutines.(*connReader) hitReadLimit() bool(*connReader) lock()(*connReader) setInfiniteReadLimit()(*connReader) setReadLimit(remain int64)(*connReader) startBackgroundRead()(*connReader) unlock()
*connReader : io.Reader
countingWriter counts how many bytes have been written to it.(*countingWriter) Write(p []byte) (n int, err error)
*countingWriter : internal/bisect.Writer
*countingWriter : io.Writer
*countingWriter : crypto/tls.transcriptHash
extraHeader is the set of headers sometimes added by chunkWriter.writeHeader.
This type is used to avoid extra allocations from cloning and/or populating
the response Header map and all its 1-element slices.connectionstring // written if not nilcontentTypestring // written if not niltransferEncodingstring Write writes the headers described in h to w.
This method has a value receiver, despite the somewhat large size
of h, because it prevents an allocation. The escape analysis isn't
smart enough to realize this function doesn't mutate h.
fakeLocker is a sync.Locker which does nothing. It's used to guard
test-only fields when not under test, to avoid runtime atomic
overhead.( fakeLocker) Lock()( fakeLocker) Unlock()
fakeLocker : sync.Locker
finishAsyncByteRead finishes reading the 1-byte sniff
from the ContentLength==0, Body!=nil case.tw*transferWriter( finishAsyncByteRead) Read(p []byte) (n int, err error)
finishAsyncByteRead : io.Reader
globalOptionsHandler responds to "OPTIONS *" requests.( globalOptionsHandler) ServeHTTP(w ResponseWriter, r *Request)
globalOptionsHandler : Handler
gzipReader wraps a response body so it can lazily
call gzip.NewReader on the first call to Read // underlying HTTP/1 response body framing // any error from gzip.NewReader; sticky // lazily-initialized gzip reader(*gzipReader) Close() error(*gzipReader) Read(p []byte) (n int, err error)
*gzipReader : io.Closer
*gzipReader : io.ReadCloser
*gzipReader : io.Reader
h2Transport is the interface we expect to be able to call from
net/http against an *http2.Transport that's either bundled into
h2_bundle.go or supplied by the user via x/net/http2.
We name it with the "h2" prefix to stay out of the "http2" prefix
namespace used by x/tools/cmd/bundle for h2_bundle.go.( h2Transport) CloseIdleConnections()
*Client
*Transporthttp2noDialH2RoundTripper
*http2Transport
A headerSorter implements sort.Interface by sorting a []keyValues
by key. It's used as a pointer, so it can fit in a sort.Interface
interface value without allocation.kvs[]keyValues(*headerSorter) Len() int(*headerSorter) Less(i, j int) bool(*headerSorter) Swap(i, j int)
*headerSorter : sort.Interface
func Header.sortedKeyValues(exclude map[string]bool) (kvs []keyValues, hs *headerSorter)
A bodyReadMsg tells the server loop that the http.Handler read n
bytes of the DATA from the client on the given stream.nintst*http2stream
bufferedWriter is a buffered writer that writes to w.
Its buffered writer is lazily allocated as needed, to minimize
idle memory usage with many connections. // non-nil when data is buffered // immutable(*http2bufferedWriter) Available() int(*http2bufferedWriter) Flush() error(*http2bufferedWriter) Write(p []byte) (n int, err error)
*http2bufferedWriter : internal/bisect.Writer
*http2bufferedWriter : io.Writer
*http2bufferedWriter : crypto/tls.transcriptHash
func http2newBufferedWriter(w io.Writer) *http2bufferedWriter
ClientConn is the state of a single HTTP/2 client connection to an
HTTP/2 server.br*bufio.Readerbw*bufio.Writerclosedboolclosingbool // hold mu; broadcast on flow/closed changes // whether conn is marked to not be reused for any future requests // our conn-level flow control quota (cs.outflow is per stream)fr*http2Framer // used by clientConnPool // if non-nil, the GoAwayFrame we received // goAway frame's debug data, retained as a string // HPACK encoder writes into thishenc*hpack.Encoder // or 0 for neveridleTimer*time.Timer // peer's conn-level flow controlinitialWindowSizeuint32lastActivetime.Time // time last idlemaxConcurrentStreamsuint32 Settings from peer: (also guarded by wmu) // guards followingnextStreamIDuint32peerMaxHeaderListSizeuint64peerMaxHeaderTableSizeuint32 // requests blocked and waiting to be sent because len(streams) == maxConcurrentStreams // in flight ping data to notification channel readLoop goroutine fields: // closed on error // set before readerDone is closed reqHeaderMu is a 1-element semaphore channel controlling access to sending new requests.
Write to reqHeaderMu to lock it, read from it to unlock.
Lock reqmu BEFORE mu or wmu. // whether conn is being reused; atomic // true if we've seen a settings frame, false otherwise // whether being used for a single http.Request // client-initiated // incr by ReserveNewRequest; decr on RoundTript*http2Transport // usually *tls.Conn, except specialized implstconnClosedbool // nil only for specialized impls // we sent a SETTINGS frame and haven't heard back // first write error that has occurred wmu is held while writing.
Acquire BEFORE mu when holding both, to avoid blocking mu on network writes.
Only acquire both at the same time when changing peer settings. CanTakeNewRequest reports whether the connection can take a new request,
meaning it has not been closed or received or sent a GOAWAY.
If the caller is going to immediately make a new request on this
connection, use ReserveNewRequest instead. Close closes the client connection immediately.
In-flight requests are interrupted. For a graceful shutdown, use Shutdown instead. Ping sends a PING frame to the server and waits for the ack. ReserveNewRequest is like CanTakeNewRequest but also reserves a
concurrent stream in cc. The reservation is decremented on the
next call to RoundTrip.(*http2ClientConn) RoundTrip(req *Request) (*Response, error) SetDoNotReuse marks cc as not reusable for future HTTP requests. Shutdown gracefully closes the client connection, waiting for running streams to complete. State returns a snapshot of cc's state. requires cc.mu be held. awaitOpenSlotForStreamLocked waits until len(streams) < maxConcurrentStreams.
Must hold cc.mu.(*http2ClientConn) canTakeNewRequestLocked() bool(*http2ClientConn) closeConn() closes the client connection immediately. In-flight requests are interrupted.
err is sent to streams. closes the client connection immediately. In-flight requests are interrupted.(*http2ClientConn) closeIfIdle() countReadFrameError calls Transport.CountError with a string
representing err.(*http2ClientConn) decrStreamReservations()(*http2ClientConn) decrStreamReservationsLocked() requires cc.wmu be held. requires cc.wmu be held. A tls.Conn.Close can hang for a long time if the peer is unresponsive.
Try to shut it down more aggressively.(*http2ClientConn) forgetStreamID(id uint32)(*http2ClientConn) healthCheck()(*http2ClientConn) idleState() http2clientConnIdleState(*http2ClientConn) idleStateLocked() (st http2clientConnIdleState)(*http2ClientConn) isDoNotReuseAndIdle() bool(*http2ClientConn) logf(format string, args ...interface{}) onIdleTimeout is called from a time.AfterFunc goroutine. It will
only be called when we're idle, but because we're coming from a new
goroutine, there could be a new request coming in at the same time,
so this simply calls the synchronized closeIfIdle to shut down this
connection. The timer could just call closeIfIdle, but this is more
clear. readLoop runs in its own goroutine and reads and dispatches frames.(*http2ClientConn) responseHeaderTimeout() time.Duration(*http2ClientConn) sendGoAway() error(*http2ClientConn) setGoAway(f *http2GoAwayFrame) tooIdleLocked reports whether this connection has been been sitting idle
for too much wall time.(*http2ClientConn) vlogf(format string, args ...interface{})(*http2ClientConn) writeHeader(name, value string) requires cc.wmu be held(*http2ClientConn) writeStreamReset(streamID uint32, code http2ErrCode, err error)
*http2ClientConn : RoundTripper
*http2ClientConn : io.Closer
func http2filterOutClientConn(in []*http2ClientConn, exclude *http2ClientConn) []*http2ClientConn
func http2filterOutClientConn(in []*http2ClientConn, exclude *http2ClientConn) []*http2ClientConn
func http2filterOutClientConn(in []*http2ClientConn, exclude *http2ClientConn) []*http2ClientConn
func http2traceGotConn(req *Request, cc *http2ClientConn, reused bool)
clientConnIdleState describes the suitability of a client
connection to initiate a new RoundTrip request.canTakeNewRequestbool
TODO: use singleflight for dialing and addConnCalls? // in-flight addConnIfNeeded calls TODO: add support for sharing conns based on cert names
(e.g. share conn for googleapis.com and appspot.com) // key is host:port // currently in-flight dialskeysmap[*http2ClientConn][]string // TODO: maybe switch to RWMutext*http2Transport(*http2clientConnPool) GetClientConn(req *Request, addr string) (*http2ClientConn, error)(*http2clientConnPool) MarkDead(cc *http2ClientConn) addConnIfNeeded makes a NewClientConn out of c if a connection for key doesn't
already exist. It coalesces concurrent calls with the same key.
This is used by the http1 Transport code when it creates a new connection. Because
the http1 Transport doesn't de-dup TCP dials to outbound hosts (because it doesn't know
the protocol), it can get into a situation where it has multiple TLS connections.
This code decides which ones live or die.
The return value used is whether c was used.
c is never closed. p.mu must be held(*http2clientConnPool) closeIdleConnections()(*http2clientConnPool) getClientConn(req *Request, addr string, dialOnMiss bool) (*http2ClientConn, error) requires p.mu is held.
*http2clientConnPool : http2ClientConnPool
*http2clientConnPool : http2clientConnPoolIdleCloser
ClientConnPool manages a pool of HTTP/2 client connections. GetClientConn returns a specific HTTP/2 connection (usually
a TLS-TCP connection) to an HTTP/2 server. On success, the
returned ClientConn accounts for the upcoming RoundTrip
call, so the caller should not omit it. If the caller needs
to, ClientConn.RoundTrip can be called with a bogus
new(http.Request) to release the stream reservation.( http2ClientConnPool) MarkDead(*http2ClientConn)
*http2clientConnPoolhttp2clientConnPoolIdleCloser(interface)http2noDialClientConnPool
clientConnPoolIdleCloser is the interface implemented by ClientConnPool
implementations which can close their idle connections. GetClientConn returns a specific HTTP/2 connection (usually
a TLS-TCP connection) to an HTTP/2 server. On success, the
returned ClientConn accounts for the upcoming RoundTrip
call, so the caller should not omit it. If the caller needs
to, ClientConn.RoundTrip can be called with a bogus
new(http.Request) to release the stream reservation.( http2clientConnPoolIdleCloser) MarkDead(*http2ClientConn)( http2clientConnPoolIdleCloser) closeIdleConnections()
*http2clientConnPoolhttp2noDialClientConnPool
http2clientConnPoolIdleCloser : http2ClientConnPool
ClientConnState describes the state of a ClientConn. Closed is whether the connection is closed. Closing is whether the connection is in the process of
closing. It may be closing due to shutdown, being a
single-use connection, being marked as DoNotReuse, or
having received a GOAWAY frame. LastIdle, if non-zero, is when the connection last
transitioned to idle state. MaxConcurrentStreams is how many concurrent streams the
peer advertised as acceptable. Zero means no SETTINGS
frame has been received yet. StreamsActive is how many streams are active. StreamsPending is how many requests have been sent in excess
of the peer's advertised MaxConcurrentStreams setting and
are waiting for other streams to complete. StreamsReserved is how many streams have been reserved via
ClientConn.ReserveNewRequest.
clientStream is the state for a single HTTP/2 stream. One of these
is created for each Transport.RoundTrip call.IDuint32 // closed to signal stream should end immediately // set if abort is closedabortOncesync.Once // buffered pipe with the flow-controlled response payload // -1 means unknown; owned by transportResponseBody.Readcc*http2ClientConn Fields of Request that we may access even after the response body is closed. // closed after the stream is in the closed state owned by clientConnReadLoop: // got the first response byte // guarded by cc.mu // guarded by cc.muisHeadbool // number of 1xx responses seen // buffered; written to if a 100 is received // got first MetaHeadersFrame (actual headers) // got optional second MetaHeadersFrame (trailers) // closed when the peer sends an END_STREAM flag // read loop reset the stream // peer sent an END_STREAM flag // sticky read error; owned by transportResponseBody.ReadreqBodyio.ReadCloser // guarded by cc.mu; non-nil on Close, closed when done // -1 means unknownreqCancel<-chan struct{}requestedGzipbool // set if respHeaderRecv is closed // client's Response.Trailer // closed when headers are received owned by writeRequest: // sent an END_STREAM flag to the peersentHeadersbool // or nil // accumulated trailers(*http2clientStream) abortRequestBodyWrite()(*http2clientStream) abortStream(err error)(*http2clientStream) abortStreamLocked(err error) awaitFlowControl waits for [1, min(maxBytes, cc.cs.maxFrameSize)] flow
control tokens from the server.
It returns either the non-zero number of tokens taken or an error
if the stream is dead. cleanupWriteRequest performs post-request tasks.
If err (the result of writeRequest) is non-nil and the stream is not closed,
cleanupWriteRequest will send a reset to the peer.(*http2clientStream) closeReqBodyLocked()(*http2clientStream) copyTrailers() doRequest runs for the duration of the request lifetime.
It sends the request and performs post-request cleanup (closing Request.Body, etc.).(*http2clientStream) encodeAndWriteHeaders(req *Request) error frameScratchBufferLen returns the length of a buffer to use for
outgoing request bodies to read/write to/from.
It returns max(1, min(peer's advertised max frame size,
Request.ContentLength+1, 512KB)). get1xxTraceFunc returns the value of request's httptrace.ClientTrace.Got1xxResponse func,
if any. It returns nil if not set or if the Go version is too old. writeRequest sends a request.
It returns nil after the request is written, the response read,
and the request stream is half-closed by the peer.
It returns non-nil if the request ends otherwise.
If the returned error is StreamError, the error Code may be used in resetting the stream.(*http2clientStream) writeRequestBody(req *Request) (err error)
A closeWaiter is like a sync.WaitGroup but only goes 1 to 0 (open to closed). Close marks the closeWaiter as closed and unblocks any waiters. Init makes a closeWaiter usable.
It exists because so a closeWaiter value can be placed inside a
larger struct and have the Mutex and Cond's memory in the same
allocation. Wait waits for the closeWaiter to become closed.
ConnectionError is an error that results in the termination of the
entire connection.( http2ConnectionError) Error() string
http2ConnectionError : error
connError represents an HTTP/2 ConnectionError error code, along
with a string (for debugging) explaining why.
Errors of this type are only returned by the frame parser functions
and converted into ConnectionError(Code), after stashing away
the Reason into the Framer's errDetail field, accessible via
the (*Framer).ErrorDetail method. // the ConnectionError error code // additional reason( http2connError) Error() string
http2connError : error
A ContinuationFrame is used to continue a sequence of header block fragments.
See https://httpwg.org/specs/rfc7540.html#rfc.section.6.10 Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type. Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement. StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0. Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame).headerFragBuf[]bytehttp2FrameHeaderhttp2FrameHeader // caller can access []byte fields in the Frame Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.(*http2ContinuationFrame) HeaderBlockFragment() []byte(*http2ContinuationFrame) HeadersEnded() bool( http2ContinuationFrame) String() string(*http2ContinuationFrame) checkValid()(*http2ContinuationFrame) invalidate()( http2ContinuationFrame) writeDebug(buf *bytes.Buffer)
http2ContinuationFrame : fmt.Stringer
*http2ContinuationFrame : http2Frame
*http2ContinuationFrame : http2headersEnder
*http2ContinuationFrame : http2headersOrContinuation
http2ContinuationFrame : context.stringer
http2ContinuationFrame : runtime.stringer
dataBuffer is an io.ReadWriter backed by a list of data chunks.
Each dataBuffer is used to read DATA frames on a single stream.
The buffer is divided into chunks so the server can limit the
total memory used by a single connection without limiting the
request body size on any single stream.chunks[][]byte // we expect at least this many bytes in future Write calls (ignored if <= 0) // next byte to read is chunks[0][r] // total buffered bytes // next byte to write is chunks[len(chunks)-1][w] Len returns the number of bytes of the unread portion of the buffer. Read copies bytes from the buffer into p.
It is an error to read when no data is available. Write appends p to the buffer.(*http2dataBuffer) bytesFromFirstChunk() []byte(*http2dataBuffer) lastChunkOrAlloc(want int64) []byte
*http2dataBuffer : internal/bisect.Writer
*http2dataBuffer : io.Reader
*http2dataBuffer : io.ReadWriter
*http2dataBuffer : io.Writer
*http2dataBuffer : http2pipeBuffer
*http2dataBuffer : crypto/tls.transcriptHash
A DataFrame conveys arbitrary, variable-length sequences of octets
associated with a stream.
See https://httpwg.org/specs/rfc7540.html#rfc.section.6.1 Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type. Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement. StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0. Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame).data[]bytehttp2FrameHeaderhttp2FrameHeader // caller can access []byte fields in the Frame Data returns the frame's data octets, not including any padding
size byte or padding suffix bytes.
The caller must not retain the returned memory past the next
call to ReadFrame. Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.(*http2DataFrame) StreamEnded() bool( http2DataFrame) String() string(*http2DataFrame) checkValid()(*http2DataFrame) invalidate()( http2DataFrame) writeDebug(buf *bytes.Buffer)
http2DataFrame : fmt.Stringer
*http2DataFrame : http2Frame
*http2DataFrame : http2streamEnder
http2DataFrame : context.stringer
http2DataFrame : runtime.stringer
dialCall is an in-flight Transport dial call to a host. the context associated with the request
that created this dialCall // closed when done // valid after done is closedp*http2clientConnPool // valid after done is closed run in its own goroutine.
func http2shouldRetryDial(call *http2dialCall, req *Request) bool
a frameParser parses a frame given its FrameHeader and payload
bytes. The length of payload will always equal fh.Length (which
might be 0).
func http2typeFrameParser(t http2FrameType) http2frameParser
A Framer reads and writes Frames. AllowIllegalReads permits the Framer's ReadFrame method
to return non-compliant frames or frame orders.
This is for testing and permits using the Framer to test
other HTTP/2 implementations' conformance to the spec.
It is not compatible with ReadMetaHeaders. AllowIllegalWrites permits the Framer's Write methods to
write frames that do not conform to the HTTP/2 spec. This
permits using the Framer to test other HTTP/2
implementations' conformance to the spec.
If false, the Write methods will prefer to return an error
rather than comply. MaxHeaderListSize is the http2 MAX_HEADER_LIST_SIZE.
It's used only if ReadMetaHeaders is set; 0 means a sane default
(currently 16MB)
If the limit is hit, MetaHeadersFrame.Truncated is set true. ReadMetaHeaders if non-nil causes ReadFrame to merge
HEADERS and CONTINUATION frames together and return
MetaHeadersFrame instead. countError is a non-nil func that's called on a frame parse
error with some unique error path token. It's initialized
from Transport.CountError or Server.CountError. // only use for logging written writesdebugFramerBuf*bytes.BufferdebugReadLoggerffunc(string, ...interface{})debugWriteLoggerffunc(string, ...interface{})errDetailerror // nil if frames aren't reused (default) TODO: let getReadBuf be configurable, and use a less memory-pinning
allocator in server.go to minimize memory pinned for many idle conns.
Will probably also need to make frame invalidation have a hook too.headerBuf[9]bytelastFramehttp2Frame lastHeaderStream is non-zero if the last frame was an
unfinished HEADERS/CONTINUATION.logReadsboollogWritesboolmaxReadSizeuint32 // zero means unlimited; TODO: implementrio.Reader // cache for default getReadBufwio.Writerwbuf[]byte ErrorDetail returns a more detailed error of the last error
returned by Framer.ReadFrame. For instance, if ReadFrame
returns a StreamError with code PROTOCOL_ERROR, ErrorDetail
will say exactly what was invalid. ErrorDetail is not guaranteed
to return a non-nil value and like the rest of the http2 package,
its return value is not protected by an API compatibility promise.
ErrorDetail is reset after the next call to ReadFrame. ReadFrame reads a single frame. The returned Frame is only valid
until the next call to ReadFrame.
If the frame is larger than previously set with SetMaxReadFrameSize, the
returned error is ErrFrameTooLarge. Other errors may be of type
ConnectionError, StreamError, or anything else from the underlying
reader. SetMaxReadFrameSize sets the maximum size of a frame
that will be read by a subsequent call to ReadFrame.
It is the caller's responsibility to advertise this
limit with a SETTINGS frame. SetReuseFrames allows the Framer to reuse Frames.
If called on a Framer, Frames returned by calls to ReadFrame are only
valid until the next call to ReadFrame. WriteContinuation writes a CONTINUATION frame.
It will perform exactly one Write to the underlying Writer.
It is the caller's responsibility to not call other Write methods concurrently. WriteData writes a DATA frame.
It will perform exactly one Write to the underlying Writer.
It is the caller's responsibility not to violate the maximum frame size
and to not call other Write methods concurrently. WriteDataPadded writes a DATA frame with optional padding.
If pad is nil, the padding bit is not sent.
The length of pad must not exceed 255 bytes.
The bytes of pad must all be zero, unless f.AllowIllegalWrites is set.
It will perform exactly one Write to the underlying Writer.
It is the caller's responsibility not to violate the maximum frame size
and to not call other Write methods concurrently.(*http2Framer) WriteGoAway(maxStreamID uint32, code http2ErrCode, debugData []byte) error WriteHeaders writes a single HEADERS frame.
This is a low-level header writing method. Encoding headers and
splitting them into any necessary CONTINUATION frames is handled
elsewhere.
It will perform exactly one Write to the underlying Writer.
It is the caller's responsibility to not call other Write methods concurrently.(*http2Framer) WritePing(ack bool, data [8]byte) error WritePriority writes a PRIORITY frame.
It will perform exactly one Write to the underlying Writer.
It is the caller's responsibility to not call other Write methods concurrently. WritePushPromise writes a single PushPromise Frame.
As with Header Frames, This is the low level call for writing
individual frames. Continuation frames are handled elsewhere.
It will perform exactly one Write to the underlying Writer.
It is the caller's responsibility to not call other Write methods concurrently. WriteRSTStream writes a RST_STREAM frame.
It will perform exactly one Write to the underlying Writer.
It is the caller's responsibility to not call other Write methods concurrently. WriteRawFrame writes a raw frame. This can be used to write
extension frames unknown to this package. WriteSettings writes a SETTINGS frame with zero or more settings
specified and the ACK bit not set.
It will perform exactly one Write to the underlying Writer.
It is the caller's responsibility to not call other Write methods concurrently. WriteSettingsAck writes an empty SETTINGS frame with the ACK bit set.
It will perform exactly one Write to the underlying Writer.
It is the caller's responsibility to not call other Write methods concurrently. WriteWindowUpdate writes a WINDOW_UPDATE frame.
The increment value must be between 1 and 2,147,483,647, inclusive.
If the Stream ID is zero, the window update applies to the
connection as a whole. checkFrameOrder reports an error if f is an invalid frame to return
next from ReadFrame. Mostly it checks whether HEADERS and
CONTINUATION frames are contiguous. connError returns ConnectionError(code) but first
stashes away a public reason to the caller can optionally relay it
to the peer before hanging up on them. This might help others debug
their implementations.(*http2Framer) endWrite() error(*http2Framer) logWrite()(*http2Framer) maxHeaderListSize() uint32(*http2Framer) maxHeaderStringLen() int readMetaFrame returns 0 or more CONTINUATION frames from fr and
merge them into the provided hf and returns a MetaHeadersFrame
with the decoded hpack values.(*http2Framer) startWrite(ftype http2FrameType, flags http2Flags, streamID uint32) startWriteDataPadded is WriteDataPadded, but only writes the frame to the Framer's internal buffer.
The caller should call endWrite to flush the frame to the underlying writer.(*http2Framer) writeByte(v byte)(*http2Framer) writeBytes(v []byte)(*http2Framer) writeUint16(v uint16)(*http2Framer) writeUint32(v uint32)
func http2NewFramer(w io.Writer, r io.Reader) *http2Framer
FrameWriteRequest is a request to write a frame. done, if non-nil, must be a buffered channel with space for
1 message and is sent the return value from write (or an
earlier error) when the frame has been written. stream is the stream on which this frame will be written.
nil for non-stream frames like PING and SETTINGS.
nil for RST_STREAM streams, which use the StreamError.StreamID field instead. write is the interface value that does the writing, once the
WriteScheduler has selected this frame to write. The write
functions are all defined in write.go. Consume consumes min(n, available) bytes from this frame, where available
is the number of flow control bytes available on the stream. Consume returns
0, 1, or 2 frames, where the integer return value gives the number of frames
returned.
If flow control prevents consuming any bytes, this returns (_, _, 0). If
the entire frame was consumed, this returns (wr, _, 1). Otherwise, this
returns (consumed, rest, 2), where 'consumed' contains the consumed bytes and
'rest' contains the remaining bytes. The consumed bytes are deducted from the
underlying stream's flow control budget. DataSize returns the number of flow control bytes that must be consumed
to write this entire frame. This is 0 for non-DATA frames. StreamID returns the id of the stream this frame will be written to.
0 is used for non-stream frames such as PING and SETTINGS. String is for debugging only. isControl reports whether wr is a control frame for MaxQueuedControlFrames
purposes. That includes non-stream frames and RST_STREAM frames. replyToWriter sends err to wr.done and panics if the send must block
This does nothing if wr.done is nil.
http2FrameWriteRequest : fmt.Stringer
http2FrameWriteRequest : context.stringer
http2FrameWriteRequest : runtime.stringer
frameWriteResult is the message passed from writeFrameAsync to the serve goroutine. // result of the writeFrame call // what was written (or attempted)
A gate lets two goroutines coordinate their activities.( http2gate) Done()( http2gate) Wait()
6.9.1 The Flow Control Window
"If a sender receives a WINDOW_UPDATE that causes a flow control
window to exceed this maximum it MUST terminate either the stream
or the connection, as appropriate. For streams, [...]; for the
connection, a GOAWAY frame with a FLOW_CONTROL_ERROR code."( http2goAwayFlowError) Error() string
http2goAwayFlowError : error
A GoAwayFrame informs the remote peer to stop creating streams on this connection.
See https://httpwg.org/specs/rfc7540.html#rfc.section.6.8ErrCodehttp2ErrCode Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type. Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement. StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0. Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame).LastStreamIDuint32debugData[]bytehttp2FrameHeaderhttp2FrameHeader // caller can access []byte fields in the Frame DebugData returns any debug data in the GOAWAY frame. Its contents
are not defined.
The caller must not retain the returned memory past the next
call to ReadFrame. Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.( http2GoAwayFrame) String() string(*http2GoAwayFrame) checkValid()(*http2GoAwayFrame) invalidate()( http2GoAwayFrame) writeDebug(buf *bytes.Buffer)
http2GoAwayFrame : fmt.Stringer
*http2GoAwayFrame : http2Frame
http2GoAwayFrame : context.stringer
http2GoAwayFrame : runtime.stringer
gzipReader wraps a response body so it can lazily
call gzip.NewReader on the first call to Read // underlying Response.Body // sticky error // lazily-initialized gzip reader(*http2gzipReader) Close() error(*http2gzipReader) Read(p []byte) (n int, err error)
*http2gzipReader : io.Closer
*http2gzipReader : io.ReadCloser
*http2gzipReader : io.Reader
A HeadersFrame is used to open a stream and additionally carries a
header block fragment. Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type. Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement. StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0. Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame). Priority is set if FlagHeadersPriority is set in the FrameHeader. // not ownedhttp2FrameHeaderhttp2FrameHeader // caller can access []byte fields in the Frame(*http2HeadersFrame) HasPriority() bool Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.(*http2HeadersFrame) HeaderBlockFragment() []byte(*http2HeadersFrame) HeadersEnded() bool(*http2HeadersFrame) StreamEnded() bool( http2HeadersFrame) String() string(*http2HeadersFrame) checkValid()(*http2HeadersFrame) invalidate()( http2HeadersFrame) writeDebug(buf *bytes.Buffer)
http2HeadersFrame : fmt.Stringer
*http2HeadersFrame : http2Frame
*http2HeadersFrame : http2headersEnder
*http2HeadersFrame : http2headersOrContinuation
*http2HeadersFrame : http2streamEnder
http2HeadersFrame : context.stringer
http2HeadersFrame : runtime.stringer
HeadersFrameParam are the parameters for writing a HEADERS frame. BlockFragment is part (or all) of a Header Block. EndHeaders indicates that this frame contains an entire
header block and is not followed by any
CONTINUATION frames. EndStream indicates that the header block is the last that
the endpoint will send for the identified stream. Setting
this flag causes the stream to enter one of "half closed"
states. PadLength is the optional number of bytes of zeros to add
to this frame. Priority, if non-zero, includes stream priority information
in the HEADER frame. StreamID is the required Stream ID to initiate.
incomparable is a zero-width, non-comparable type. Adding it to a struct
makes that struct also non-comparable, and generally doesn't add
any size (as long as it's first).
inflow accounts for an inbound flow control window.
It tracks both the latest window sent to the peer (used for enforcement)
and the accumulated unsent window.availint32unsentint32 add adds n bytes to the window, with a maximum window size of max,
indicating that the peer can now send us more data.
For example, the user read from a {Request,Response} body and consumed
some of the buffered data, so the peer can now send more.
It returns the number of bytes to send in a WINDOW_UPDATE frame to the peer.
Window updates are accumulated and sent when the unsent capacity
is at least inflowMinRefresh or will at least double the peer's available window. init sets the initial window. take attempts to take n bytes from the peer's flow control window.
It reports whether the window has available capacity.
func http2takeInflows(f1, f2 *http2inflow, n uint32) bool
A MetaHeadersFrame is the representation of one HEADERS frame and
zero or more contiguous CONTINUATION frames and the decoding of
their HPACK-encoded contents.
This type of frame does not appear on the wire and is only returned
by the Framer when Framer.ReadMetaHeaders is set. Fields are the fields contained in the HEADERS and
CONTINUATION frames. The underlying slice is owned by the
Framer and must not be retained after the next call to
ReadFrame.
Fields are guaranteed to be in the correct http2 order and
not have unknown pseudo header fields or invalid header
field names or values. Required pseudo header fields may be
missing, however. Use the MetaHeadersFrame.Pseudo accessor
method access pseudo headers. Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type. Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement. StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0. Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame). Priority is set if FlagHeadersPriority is set in the FrameHeader. Truncated is whether the max header list size limit was hit
and Fields is incomplete. The hpack decoder state is still
valid, however.http2HeadersFrame*http2HeadersFrame // not ownedhttp2HeadersFrame.http2FrameHeaderhttp2FrameHeader // caller can access []byte fields in the Frame( http2MetaHeadersFrame) HasPriority() bool Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.( http2MetaHeadersFrame) HeaderBlockFragment() []byte( http2MetaHeadersFrame) HeadersEnded() bool PseudoFields returns the pseudo header fields of mh.
The caller does not own the returned slice. PseudoValue returns the given pseudo header field's value.
The provided pseudo field should not contain the leading colon. RegularFields returns the regular (non-pseudo) header fields of mh.
The caller does not own the returned slice.( http2MetaHeadersFrame) StreamEnded() bool( http2MetaHeadersFrame) String() string(*http2MetaHeadersFrame) checkPseudos() error( http2MetaHeadersFrame) checkValid()( http2MetaHeadersFrame) invalidate()( http2MetaHeadersFrame) writeDebug(buf *bytes.Buffer)
http2MetaHeadersFrame : fmt.Stringer
http2MetaHeadersFrame : http2Frame
http2MetaHeadersFrame : http2headersEnder
http2MetaHeadersFrame : http2headersOrContinuation
http2MetaHeadersFrame : http2streamEnder
http2MetaHeadersFrame : context.stringer
http2MetaHeadersFrame : runtime.stringer
noCachedConnError is the concrete type of ErrNoCachedConn, which
needs to be detected by net/http regardless of whether it's its
bundled version (in h2_bundle.go with a rewritten type name) or
from a user's x/net/http2. As such, as it has a unique method name
(IsHTTP2NoCachedConnError) that net/http sniffs for via func
isNoCachedConnError.( http2noCachedConnError) Error() string( http2noCachedConnError) IsHTTP2NoCachedConnError()
http2noCachedConnError : error
noDialClientConnPool is an implementation of http2.ClientConnPool
which never dials. We let the HTTP/1.1 client dial and use its TLS
connection instead.http2clientConnPool*http2clientConnPool // in-flight addConnIfNeeded calls TODO: add support for sharing conns based on cert names
(e.g. share conn for googleapis.com and appspot.com) // key is host:port // currently in-flight dialshttp2clientConnPool.keysmap[*http2ClientConn][]string // TODO: maybe switch to RWMutexhttp2clientConnPool.t*http2Transport( http2noDialClientConnPool) GetClientConn(req *Request, addr string) (*http2ClientConn, error)( http2noDialClientConnPool) MarkDead(cc *http2ClientConn) addConnIfNeeded makes a NewClientConn out of c if a connection for key doesn't
already exist. It coalesces concurrent calls with the same key.
This is used by the http1 Transport code when it creates a new connection. Because
the http1 Transport doesn't de-dup TCP dials to outbound hosts (because it doesn't know
the protocol), it can get into a situation where it has multiple TLS connections.
This code decides which ones live or die.
The return value used is whether c was used.
c is never closed. p.mu must be held( http2noDialClientConnPool) closeIdleConnections()( http2noDialClientConnPool) getClientConn(req *Request, addr string, dialOnMiss bool) (*http2ClientConn, error) requires p.mu is held.
http2noDialClientConnPool : http2ClientConnPool
http2noDialClientConnPool : http2clientConnPoolIdleCloser
noDialH2RoundTripper is a RoundTripper which only tries to complete the request
if there's already has a cached connection to the host.
(The field is exported so it can be accessed via reflect from net/http; tested
by TestNoDialH2RoundTripperType) AllowHTTP, if true, permits HTTP/2 requests using the insecure,
plain-text "http" scheme. Note that this does not enable h2c support. ConnPool optionally specifies an alternate connection pool to use.
If nil, the default is used. CountError, if non-nil, is called on HTTP/2 transport errors.
It's intended to increment a metric for monitoring, such
as an expvar or Prometheus metric.
The errType consists of only ASCII word characters. DialTLS specifies an optional dial function for creating
TLS connections for requests.
If DialTLSContext and DialTLS is nil, tls.Dial is used.
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. DialTLSContext specifies an optional dial function with context for
creating TLS connections for requests.
If DialTLSContext and DialTLS is nil, tls.Dial is used.
If the returned net.Conn has a ConnectionState method like tls.Conn,
it will be used to set http.Response.TLS. 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. MaxDecoderHeaderTableSize optionally specifies the http2
SETTINGS_HEADER_TABLE_SIZE to send in the initial settings frame. It
informs the remote endpoint of the maximum size of the header compression
table used to decode header blocks, in octets. If zero, the default value
of 4096 is used. MaxEncoderHeaderTableSize optionally specifies an upper limit for the
header compression table used for encoding request headers. Received
SETTINGS_HEADER_TABLE_SIZE settings are capped at this limit. If zero,
the default value of 4096 is used. MaxHeaderListSize is the http2 SETTINGS_MAX_HEADER_LIST_SIZE to
send in the initial settings frame. It is how many bytes
of response headers are allowed. Unlike the http2 spec, zero here
means to use a default limit (currently 10MB). If you actually
want to advertise an unlimited value to the peer, Transport
interprets the highest possible value here (0xffffffff or 1<<32-1)
to mean no limit. MaxReadFrameSize is the http2 SETTINGS_MAX_FRAME_SIZE to send in the
initial settings frame. It is the size in bytes of the largest frame
payload that the sender is willing to receive. If 0, no setting is
sent, and the value is provided by the peer, which should be 16384
according to the spec:
https://datatracker.ietf.org/doc/html/rfc7540#section-6.5.2.
Values are bounded in the range 16k to 16M. PingTimeout is the timeout after which the connection will be closed
if a response to Ping is not received.
Defaults to 15s. ReadIdleTimeout is the timeout after which a health check using ping
frame will be carried out if no frame is received on the connection.
Note that a ping response will is considered a received frame, so if
there is no other traffic on the connection, the health check will
be performed every ReadIdleTimeout interval.
If zero, no health check is performed. StrictMaxConcurrentStreams controls whether the server's
SETTINGS_MAX_CONCURRENT_STREAMS should be respected
globally. If false, new TCP connections are created to the
server as needed to keep each under the per-connection
SETTINGS_MAX_CONCURRENT_STREAMS limit. If true, the
server's SETTINGS_MAX_CONCURRENT_STREAMS is interpreted as
a global limit and callers of RoundTrip block when needed,
waiting for their turn. TLSClientConfig specifies the TLS configuration to use with
tls.Client. If nil, the default configuration is used. WriteByteTimeout is the timeout after which the connection will be
closed no data can be written to it. The timeout begins when data is
available to write, and is extended whenever any bytes are written.http2Transport*http2Transporthttp2Transport.connPoolOncesync.Once // non-nil version of ConnPool t1, if non-nil, is the standard library Transport using
this transport. Its settings are used (but not its
RoundTrip method, etc). CloseIdleConnections closes any connections which were previously
connected from previous requests but are now sitting idle.
It does not interrupt any connections currently in use.( http2noDialH2RoundTripper) NewClientConn(c net.Conn) (*http2ClientConn, error)( http2noDialH2RoundTripper) RoundTrip(req *Request) (*Response, error) RoundTripOpt is like RoundTrip, but takes options.( http2noDialH2RoundTripper) connPool() http2ClientConnPool( http2noDialH2RoundTripper) dialClientConn(ctx context.Context, addr string, singleUse bool) (*http2ClientConn, error)( http2noDialH2RoundTripper) dialTLS(ctx context.Context, network, addr string, tlsCfg *tls.Config) (net.Conn, error) dialTLSWithContext uses tls.Dialer, added in Go 1.15, to open a TLS
connection.( http2noDialH2RoundTripper) disableCompression() bool disableKeepAlives reports whether connections should be closed as
soon as possible after handling the first request.( http2noDialH2RoundTripper) expectContinueTimeout() time.Duration( http2noDialH2RoundTripper) idleConnTimeout() time.Duration( http2noDialH2RoundTripper) initConnPool()( http2noDialH2RoundTripper) logf(format string, args ...interface{})( http2noDialH2RoundTripper) maxDecoderHeaderTableSize() uint32( http2noDialH2RoundTripper) maxEncoderHeaderTableSize() uint32( http2noDialH2RoundTripper) maxFrameReadSize() uint32( http2noDialH2RoundTripper) maxHeaderListSize() uint32( http2noDialH2RoundTripper) newClientConn(c net.Conn, singleUse bool) (*http2ClientConn, error)( http2noDialH2RoundTripper) newTLSConfig(host string) *tls.Config( http2noDialH2RoundTripper) pingTimeout() time.Duration( http2noDialH2RoundTripper) vlogf(format string, args ...interface{})
http2noDialH2RoundTripper : RoundTripper
http2noDialH2RoundTripper : h2Transport
func http2registerHTTPSProtocol(t *Transport, rt http2noDialH2RoundTripper) (err error)
OpenStreamOptions specifies extra options for WriteScheduler.OpenStream. PusherID is zero if the stream was initiated by the client. Otherwise,
PusherID names the stream that pushed the newly opened stream.
outflow is the outbound flow control window's size. conn points to the shared connection-level outflow that is
shared by all streams on that conn. It is nil for the outflow
that's on the conn directly. n is the number of DATA bytes we're allowed to send.
An outflow is kept both on a conn and a per-stream. add adds n bytes (positive or negative) to the flow control window.
It returns false if the sum would exceed 2^31-1.(*http2outflow) available() int32(*http2outflow) setConnFlow(cf *http2outflow)(*http2outflow) take(n int32)
A PingFrame is a mechanism for measuring a minimal round trip time
from the sender, as well as determining whether an idle connection
is still functional.
See https://httpwg.org/specs/rfc7540.html#rfc.section.6.7Data[8]byte Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type. Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement. StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0. Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame).http2FrameHeaderhttp2FrameHeader // caller can access []byte fields in the Frame Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.(*http2PingFrame) IsAck() bool( http2PingFrame) String() string(*http2PingFrame) checkValid()(*http2PingFrame) invalidate()( http2PingFrame) writeDebug(buf *bytes.Buffer)
http2PingFrame : fmt.Stringer
*http2PingFrame : http2Frame
http2PingFrame : context.stringer
http2PingFrame : runtime.stringer
pipe is a goroutine-safe io.Reader/io.Writer pair. It's like
io.Pipe except there are no PipeReader/PipeWriter halves, and the
underlying buffer is an interface. (io.Pipe is always unbuffered) // nil when done reading // immediate read error (caller doesn't see rest of b) // c.L lazily initialized to &p.mu // closed on error // read error once empty. non-nil means closed.musync.Mutex // optional code to run in Read before error // bytes unread when done BreakWithError causes the next Read (waking up a current blocked
Read if needed) to return the provided err immediately, without
waiting for unread data. CloseWithError causes the next Read (waking up a current blocked
Read if needed) to return the provided err after all data has been
read.
The error must be non-nil. Done returns a channel which is closed if and when this pipe is closed
with CloseWithError. Err returns the error (if any) first set by BreakWithError or CloseWithError.(*http2pipe) Len() int Read waits until data is available and copies bytes
from the buffer into p. Write copies bytes from p into the buffer and wakes a reader.
It is an error to write more data than the buffer can hold. requires p.mu be held.(*http2pipe) closeWithError(dst *error, err error, fn func()) closeWithErrorAndCode is like CloseWithError but also sets some code to run
in the caller's goroutine before returning the error. setBuffer initializes the pipe buffer.
It has no effect if the pipe is already closed.
*http2pipe : internal/bisect.Writer
*http2pipe : io.Reader
*http2pipe : io.ReadWriter
*http2pipe : io.Writer
*http2pipe : http2pipeBuffer
*http2pipe : crypto/tls.transcriptHash
A PriorityFrame specifies the sender-advised priority of a stream.
See https://httpwg.org/specs/rfc7540.html#rfc.section.6.3 Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type. Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement. StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0. Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame). Exclusive is whether the dependency is exclusive. StreamDep is a 31-bit stream identifier for the
stream that this stream depends on. Zero means no
dependency. Weight is the stream's zero-indexed weight. It should be
set together with StreamDep, or neither should be set. Per
the spec, "Add one to the value to obtain a weight between
1 and 256."http2FrameHeaderhttp2FrameHeader // caller can access []byte fields in the Framehttp2PriorityParamhttp2PriorityParam Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.( http2PriorityFrame) IsZero() bool( http2PriorityFrame) String() string(*http2PriorityFrame) checkValid()(*http2PriorityFrame) invalidate()( http2PriorityFrame) writeDebug(buf *bytes.Buffer)
http2PriorityFrame : fmt.Stringer
*http2PriorityFrame : http2Frame
http2PriorityFrame : context.stringer
http2PriorityFrame : runtime.stringer
priorityNode is a node in an HTTP/2 priority tree.
Each node is associated with a single stream ID.
See RFC 7540, Section 5.3. // number of bytes written by this node, or 0 if closed // id of the stream, or 0 for the root of the tree // start of the kids list // doubly-linked list of siblings These links form the priority tree. // doubly-linked list of siblings // queue of pending frames to write // open | closed | idle // sum(node.bytes) of all nodes in this subtree // the actual weight is weight+1, so the value is in [1,256](*http2priorityNode) addBytes(b int64)(*http2priorityNode) setParent(parent *http2priorityNode) walkReadyInOrder iterates over the tree in priority order, calling f for each node
with a non-empty write queue. When f returns true, this function returns true and the
walk halts. tmp is used as scratch space for sorting.
f(n, openParent) takes two arguments: the node to visit, n, and a bool that is true
if any ancestor p of n is still open (ignoring the root node).
PriorityParam are the stream prioritzation parameters. Exclusive is whether the dependency is exclusive. StreamDep is a 31-bit stream identifier for the
stream that this stream depends on. Zero means no
dependency. Weight is the stream's zero-indexed weight. It should be
set together with StreamDep, or neither should be set. Per
the spec, "Add one to the value to obtain a weight between
1 and 256."( http2PriorityParam) IsZero() bool
lists of nodes that have been closed or are idle, but are kept in
the tree for improved prioritization. When the lengths exceed either
maxClosedNodesInTree or maxIdleNodesInTree, old nodes are discarded.enableWriteThrottlebool lists of nodes that have been closed or are idle, but are kept in
the tree for improved prioritization. When the lengths exceed either
maxClosedNodesInTree or maxIdleNodesInTree, old nodes are discarded. From the config. maxID is the maximum stream id in nodes.maxIdleNodesInTreeint nodes maps stream ids to priority tree nodes. pool of empty queues for reuse. root is the root of the priority tree, where root.id = 0.
The root queues control frames that are not associated with any stream. tmp is scratch space for priorityNode.walkReadyInOrder to reduce allocations.writeThrottleLimitint32(*http2priorityWriteScheduler) AdjustStream(streamID uint32, priority http2PriorityParam)(*http2priorityWriteScheduler) CloseStream(streamID uint32)(*http2priorityWriteScheduler) OpenStream(streamID uint32, options http2OpenStreamOptions)(*http2priorityWriteScheduler) Pop() (wr http2FrameWriteRequest, ok bool)(*http2priorityWriteScheduler) Push(wr http2FrameWriteRequest)(*http2priorityWriteScheduler) addClosedOrIdleNode(list *[]*http2priorityNode, maxSize int, n *http2priorityNode)(*http2priorityWriteScheduler) removeNode(n *http2priorityNode)
*http2priorityWriteScheduler : http2WriteScheduler
PriorityWriteSchedulerConfig configures a priorityWriteScheduler. MaxClosedNodesInTree controls the maximum number of closed streams to
retain in the priority tree. Setting this to zero saves a small amount
of memory at the cost of performance.
See RFC 7540, Section 5.3.4:
"It is possible for a stream to become closed while prioritization
information ... is in transit. ... This potentially creates suboptimal
prioritization, since the stream could be given a priority that is
different from what is intended. To avoid these problems, an endpoint
SHOULD retain stream prioritization state for a period after streams
become closed. The longer state is retained, the lower the chance that
streams are assigned incorrect or default priority values." MaxIdleNodesInTree controls the maximum number of idle streams to
retain in the priority tree. Setting this to zero saves a small amount
of memory at the cost of performance.
See RFC 7540, Section 5.3.4:
Similarly, streams that are in the "idle" state can be assigned
priority or become a parent of other streams. This allows for the
creation of a grouping node in the dependency tree, which enables
more flexible expressions of priority. Idle streams begin with a
default priority (Section 5.3.5). ThrottleOutOfOrderWrites enables write throttling to help ensure that
data is delivered in priority order. This works around a race where
stream B depends on stream A and both streams are about to call Write
to queue DATA frames. If B wins the race, a naive scheduler would eagerly
write as much data from B as possible, but this is suboptimal because A
is a higher-priority stream. With throttling enabled, we write a small
amount of data from B to minimize the amount of bandwidth that B can
steal from A.
func http2NewPriorityWriteScheduler(cfg *http2PriorityWriteSchedulerConfig) http2WriteScheduler
A PushPromiseFrame is used to initiate a server stream.
See https://httpwg.org/specs/rfc7540.html#rfc.section.6.6 Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type. Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement. StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0. Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame).PromiseIDuint32 // not ownedhttp2FrameHeaderhttp2FrameHeader // caller can access []byte fields in the Frame Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.(*http2PushPromiseFrame) HeaderBlockFragment() []byte(*http2PushPromiseFrame) HeadersEnded() bool( http2PushPromiseFrame) String() string(*http2PushPromiseFrame) checkValid()(*http2PushPromiseFrame) invalidate()( http2PushPromiseFrame) writeDebug(buf *bytes.Buffer)
http2PushPromiseFrame : fmt.Stringer
*http2PushPromiseFrame : http2Frame
*http2PushPromiseFrame : http2headersEnder
*http2PushPromiseFrame : http2headersOrContinuation
http2PushPromiseFrame : context.stringer
http2PushPromiseFrame : runtime.stringer
PushPromiseParam are the parameters for writing a PUSH_PROMISE frame. BlockFragment is part (or all) of a Header Block. EndHeaders indicates that this frame contains an entire
header block and is not followed by any
CONTINUATION frames. PadLength is the optional number of bytes of zeros to add
to this frame. PromiseID is the required Stream ID which this
Push Promises StreamID is the required Stream ID to initiate.
errerror // valid until readMore is called readMore should be called once the consumer no longer needs or
retains f. After readMore, f is invalid and more frames can be
read.
requestBody is the Handler's Request.Body type.
Read and Close may be called concurrently. // for use by Close onlyconn*http2serverConn // need to send a 100-continue // non-nil if we have an HTTP entity message body // for use by Read onlystream*http2stream(*http2requestBody) Close() error(*http2requestBody) Read(p []byte) (n int, err error)
*http2requestBody : io.Closer
*http2requestBody : io.ReadCloser
*http2requestBody : io.Reader
responseWriter is the http.ResponseWriter implementation. It's
intentionally small (1 pointer wide) to minimize garbage. The
responseWriterState pointer inside is zeroed at the end of a
request (in handlerDone) and calls on the responseWriter thereafter
simply crash (caller's mistake), but the much larger responseWriterState
and buffers are reused between multiple requests.rws*http2responseWriterState(*http2responseWriter) CloseNotify() <-chan bool(*http2responseWriter) Flush()(*http2responseWriter) FlushError() error(*http2responseWriter) Header() Header(*http2responseWriter) Push(target string, opts *PushOptions) error(*http2responseWriter) SetReadDeadline(deadline time.Time) error(*http2responseWriter) SetWriteDeadline(deadline time.Time) error The Life Of A Write is like this:
* Handler calls w.Write or w.WriteString ->
* -> rws.bw (*bufio.Writer) ->
* (Handler might call Flush)
* -> chunkWriter{rws}
* -> responseWriterState.writeChunk(p []byte)
* -> responseWriterState.writeChunk (most of the magic; see comment there)(*http2responseWriter) WriteHeader(code int)(*http2responseWriter) WriteString(s string) (n int, err error)(*http2responseWriter) handlerDone() either dataB or dataS is non-zero.
*http2responseWriter : CloseNotifier
*http2responseWriter : Flusher
*http2responseWriter : Pusher
*http2responseWriter : ResponseWriter
*http2responseWriter : internal/bisect.Writer
*http2responseWriter : io.StringWriter
*http2responseWriter : io.Writer
*http2responseWriter : http2stringWriter
*http2responseWriter : crypto/tls.transcriptHash
TODO: adjust buffer writing sizes based on server config, frame size updates from peer, etc // writing to a chunkWriter{this *responseWriterState} // nil until first used // guards closeNotifierChconn*http2serverConn // a Write failed; don't reuse this responseWriterState // handler has finished mutated by http.Handler goroutine: // nil until calledreq*Request // non-zero if handler set a Content-Length header // have we sent the header frame? // snapshot of handlerHeader at WriteHeader time // status code passed to WriteHeader immutable within a request: // set in writeChunkwroteBytesint64 // WriteHeader called (explicitly or implicitly). Not necessarily sent to user yet. declareTrailer is called for each Trailer header when the
response header is written. It notes that a header will need to be
written in the trailers at the end of the response.(*http2responseWriterState) hasNonemptyTrailers() bool(*http2responseWriterState) hasTrailers() bool promoteUndeclaredTrailers permits http.Handlers to set trailers
after the header has already been flushed. Because the Go
ResponseWriter interface has no way to set Trailers (only the
Header), and because we didn't want to expand the ResponseWriter
interface, and because nobody used trailers, and because RFC 7230
says you SHOULD (but not must) predeclare any trailers in the
header, the official ResponseWriter rules said trailers in Go must
be predeclared, and then we reuse the same ResponseWriter.Header()
map to mean both Headers and Trailers. When it's time to write the
Trailers, we pick out the fields of Headers that were declared as
trailers. That worked for a while, until we found the first major
user of Trailers in the wild: gRPC (using them only over http2),
and gRPC libraries permit setting trailers mid-stream without
predeclaring them. So: change of plans. We still permit the old
way, but we also permit this hack: if a Header() key begins with
"Trailer:", the suffix of that key is a Trailer. Because ':' is an
invalid token byte anyway, there is no ambiguity. (And it's already
filtered out) It's mildly hacky, but not terrible.
This method runs after the Handler is done and promotes any Header
fields to be trailers. writeChunk writes chunks from the bufio.Writer. But because
bufio.Writer may bypass its chunking, sometimes p may be
arbitrarily large.
writeChunk is also responsible (on the first chunk) for sending the
HEADER response.(*http2responseWriterState) writeHeader(code int)
control contains control frames (SETTINGS, PING, etc.). stream queues are stored in a circular linked list.
head is the next stream to write, or nil if there are no streams open. pool of empty queues for reuse. streams maps stream ID to a queue.(*http2roundRobinWriteScheduler) AdjustStream(streamID uint32, priority http2PriorityParam)(*http2roundRobinWriteScheduler) CloseStream(streamID uint32)(*http2roundRobinWriteScheduler) OpenStream(streamID uint32, options http2OpenStreamOptions)(*http2roundRobinWriteScheduler) Pop() (http2FrameWriteRequest, bool)(*http2roundRobinWriteScheduler) Push(wr http2FrameWriteRequest)
*http2roundRobinWriteScheduler : http2WriteScheduler
RoundTripOpt are options for the Transport.RoundTripOpt method. OnlyCachedConn controls whether RoundTripOpt may
create a new TCP connection. If set true and
no cached connection is available, RoundTripOpt
will return ErrNoCachedConn.
A RSTStreamFrame allows for abnormal termination of a stream.
See https://httpwg.org/specs/rfc7540.html#rfc.section.6.4ErrCodehttp2ErrCode Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type. Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement. StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0. Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame).http2FrameHeaderhttp2FrameHeader // caller can access []byte fields in the Frame Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.( http2RSTStreamFrame) String() string(*http2RSTStreamFrame) checkValid()(*http2RSTStreamFrame) invalidate()( http2RSTStreamFrame) writeDebug(buf *bytes.Buffer)
http2RSTStreamFrame : fmt.Stringer
*http2RSTStreamFrame : http2Frame
http2RSTStreamFrame : context.stringer
http2RSTStreamFrame : runtime.stringer
ServeConnOpts are options for the Server.ServeConn method. BaseConfig optionally sets the base configuration
for values. If nil, defaults are used. Context is the base context to use.
If nil, context.Background is used. Handler specifies which handler to use for processing
requests. If nil, BaseConfig.Handler is used. If BaseConfig
or BaseConfig.Handler is nil, http.DefaultServeMux is used. SawClientPreface is set if the HTTP/2 connection preface
has already been read from the connection. Settings is the decoded contents of the HTTP2-Settings header
in an h2c upgrade request. UpgradeRequest is an initial request received on a connection
undergoing an h2c upgrade. The request body must have been
completely read from the connection before calling ServeConn,
and the 101 Switching Protocols response written.(*http2ServeConnOpts) baseConfig() *Server(*http2ServeConnOpts) context() context.Context(*http2ServeConnOpts) handler() Handler
func http2serverConnBaseContext(c net.Conn, opts *http2ServeConnOpts) (ctx context.Context, cancel func())
Server is an HTTP/2 server. CountError, if non-nil, is called on HTTP/2 server errors.
It's intended to increment a metric for monitoring, such
as an expvar or Prometheus metric.
The errType consists of only ASCII word characters. IdleTimeout specifies how long until idle clients should be
closed with a GOAWAY frame. PING frames are not considered
activity for the purposes of IdleTimeout. MaxConcurrentStreams optionally specifies the number of
concurrent streams that each client may have open at a
time. This is unrelated to the number of http.Handler goroutines
which may be active globally, which is MaxHandlers.
If zero, MaxConcurrentStreams defaults to at least 100, per
the HTTP/2 spec's recommendations. MaxDecoderHeaderTableSize optionally specifies the http2
SETTINGS_HEADER_TABLE_SIZE to send in the initial settings frame. It
informs the remote endpoint of the maximum size of the header compression
table used to decode header blocks, in octets. If zero, the default value
of 4096 is used. MaxEncoderHeaderTableSize optionally specifies an upper limit for the
header compression table used for encoding request headers. Received
SETTINGS_HEADER_TABLE_SIZE settings are capped at this limit. If zero,
the default value of 4096 is used. MaxHandlers limits the number of http.Handler ServeHTTP goroutines
which may run at a time over all connections.
Negative or zero no limit.
TODO: implement MaxReadFrameSize optionally specifies the largest frame
this server is willing to read. A valid value is between
16k and 16M, inclusive. If zero or otherwise invalid, a
default value is used. MaxUploadBufferPerConnection is the size of the initial flow
control window for each connections. The HTTP/2 spec does not
allow this to be smaller than 65535 or larger than 2^32-1.
If the value is outside this range, a default value will be
used instead. MaxUploadBufferPerStream is the size of the initial flow control
window for each stream. The HTTP/2 spec does not allow this to
be larger than 2^32-1. If the value is zero or larger than the
maximum, a default value will be used instead. NewWriteScheduler constructs a write scheduler for a connection.
If nil, a default scheduler is chosen. PermitProhibitedCipherSuites, if true, permits the use of
cipher suites prohibited by the HTTP/2 spec. Internal state. This is a pointer (rather than embedded directly)
so that we don't embed a Mutex in this struct, which will make the
struct non-copyable, which might break some callers. ServeConn serves HTTP/2 requests on the provided connection and
blocks until the connection is no longer readable.
ServeConn starts speaking HTTP/2 assuming that c has not had any
reads or writes. It writes its initial settings frame and expects
to be able to read the preface and settings frame from the
client. If c has a ConnectionState method like a *tls.Conn, the
ConnectionState is used to verify the TLS ciphersuite and to set
the Request.TLS field in Handlers.
ServeConn does not support h2c by itself. Any h2c support must be
implemented in terms of providing a suitably-behaving net.Conn.
The opts parameter is optional. If nil, default values are used.(*http2Server) initialConnRecvWindowSize() int32(*http2Server) initialStreamRecvWindowSize() int32(*http2Server) maxConcurrentStreams() uint32(*http2Server) maxDecoderHeaderTableSize() uint32(*http2Server) maxEncoderHeaderTableSize() uint32 maxQueuedControlFrames is the maximum number of control frames like
SETTINGS, PING and RST_STREAM that will be queued for writing before
the connection is closed to prevent memory exhaustion attacks.(*http2Server) maxReadFrameSize() uint32
func http2ConfigureServer(s *Server, conf *http2Server) error
// our SETTINGS_MAX_CONCURRENT_STREAMS advertised the clientbaseCtxcontext.Context // from handlers -> serve // writing to conn // http2-lower-case -> Go-Canonical-Case // canonHeader keys size in bytes // SETTINGS_MAX_CONCURRENT_STREAMS from client (our PUSH_PROMISE limit)connnet.Conn // number of open streams initiated by the client // number of running handler goroutines // number of open streams initiated by server push // closed when serverConn.serve ends // conn-wide (not stream-specific) outbound flow controlframer*http2FramergoAwayCodehttp2ErrCodehandlerHandler Owned by the writeFrameAsync goroutine:hpackEncoder*hpack.Encoderhs*Server // nil if unused // whether we're in the scheduleFrameWrite loop // we've started to or sent GOAWAY // conn-wide inbound flow controlinitialStreamSendWindowSizeint32 // max ever seen from client (odd), or 0 if there have been no client requestsmaxFrameSizeint32 // ID of the last push promise (even), or 0 if there have been no pushes // we need to schedule a GOAWAY frame writeneedToSendSettingsAckbool // last frame write wasn't a flush // zero means unknown (default)pushEnabledbool // control frames in the writeSched queue // written by serverConn.readFramesremoteAddrStrstring // preface has already been read, used in h2c upgrade // got the initial SETTINGS frame after the preface Everything following is owned by the serve loop; use serveG.check(): // used to verify funcs are on serve() // misc messages & code to send to / run on the serve loop Used by startGracefulShutdown. // nil until used Immutable:streamsmap[uint32]*http2stream // shared by all handlers, like net/http // how many SETTINGS have we sent without ACKs?unstartedHandlers[]http2unstartedHandler // from handlers -> servewriteSchedhttp2WriteScheduler // started writing a frame (on serve goroutine or separate) // started a frame on its own goroutine but haven't heard back on wroteFrameCh // from writeFrameAsync -> serve, tickles more frame writes(*http2serverConn) CloseConn() error(*http2serverConn) Flush() error(*http2serverConn) Framer() *http2Framer(*http2serverConn) HeaderEncoder() (*hpack.Encoder, *bytes.Buffer)(*http2serverConn) awaitGracefulShutdown(sharedCh <-chan struct{}, privateCh chan struct{})(*http2serverConn) canonicalHeader(v string) string(*http2serverConn) checkPriority(streamID uint32, p http2PriorityParam) error(*http2serverConn) closeAllStreamsOnConnClose()(*http2serverConn) closeStream(st *http2stream, err error)(*http2serverConn) condlogf(err error, format string, args ...interface{})(*http2serverConn) countError(name string, err error) error(*http2serverConn) curOpenStreams() uint32(*http2serverConn) goAway(code http2ErrCode)(*http2serverConn) handlerDone()(*http2serverConn) logf(format string, args ...interface{})(*http2serverConn) maxHeaderListSize() uint32(*http2serverConn) newResponseWriter(st *http2stream, req *Request) *http2responseWriter(*http2serverConn) newStream(id, pusherID uint32, state http2streamState) *http2stream(*http2serverConn) newWriterAndRequest(st *http2stream, f *http2MetaHeadersFrame) (*http2responseWriter, *Request, error)(*http2serverConn) newWriterAndRequestNoBody(st *http2stream, rp http2requestParam) (*http2responseWriter, *Request, error)(*http2serverConn) noteBodyRead(st *http2stream, n int) called from handler goroutines.
Notes that the handler for the given stream ID read n bytes of its body
and schedules flow control tokens to be sent.(*http2serverConn) notePanic()(*http2serverConn) onIdleTimer()(*http2serverConn) onSettingsTimer()(*http2serverConn) onShutdownTimer()(*http2serverConn) processData(f *http2DataFrame) error(*http2serverConn) processFrame(f http2Frame) error processFrameFromReader processes the serve loop's read from readFrameCh from the
frame-reading goroutine.
processFrameFromReader returns whether the connection should be kept open.(*http2serverConn) processGoAway(f *http2GoAwayFrame) error(*http2serverConn) processHeaders(f *http2MetaHeadersFrame) error(*http2serverConn) processPing(f *http2PingFrame) error(*http2serverConn) processPriority(f *http2PriorityFrame) error(*http2serverConn) processResetStream(f *http2RSTStreamFrame) error(*http2serverConn) processSetting(s http2Setting) error(*http2serverConn) processSettingInitialWindowSize(val uint32) error(*http2serverConn) processSettings(f *http2SettingsFrame) error(*http2serverConn) processWindowUpdate(f *http2WindowUpdateFrame) error readFrames is the loop that reads incoming frames.
It takes care to only read one frame at a time, blocking until the
consumer is done with the frame.
It's run on its own goroutine. readPreface reads the ClientPreface greeting from the peer or
returns errPrefaceTimeout on timeout, or an error if the greeting
is invalid.(*http2serverConn) rejectConn(err http2ErrCode, debug string)(*http2serverConn) resetStream(se http2StreamError) Run on its own goroutine. scheduleFrameWrite tickles the frame writing scheduler.
If a frame is already being written, nothing happens. This will be called again
when the frame is done being written.
If a frame isn't being written and we need to send one, the best frame
to send is selected by writeSched.
If a frame isn't being written and there's nothing else to send, we
flush the write buffer. scheduleHandler starts a handler goroutine,
or schedules one to start as soon as an existing handler finishes.(*http2serverConn) sendServeMsg(msg interface{}) st may be nil for conn-level st may be nil for conn-level(*http2serverConn) serve() setConnState calls the net/http ConnState hook for this connection, if configured.
Note that the net/http package does StateNew and StateClosed for us.
There is currently no plan for StateHijacked or hijacking HTTP/2 connections.(*http2serverConn) shutDownIn(d time.Duration) startFrameWrite starts a goroutine to write wr (in a separate
goroutine since that might block on the network), and updates the
serve goroutine's state about the world, updated from info in wr. startGracefulShutdown gracefully shuts down a connection. This
sends GOAWAY with ErrCodeNo to tell the client we're gracefully
shutting down. The connection isn't closed until all current
streams are done.
startGracefulShutdown returns immediately; it does not wait until
the connection has shut down.(*http2serverConn) startGracefulShutdownInternal()(*http2serverConn) startPush(msg *http2startPushRequest)(*http2serverConn) state(streamID uint32) (http2streamState, *http2stream)(*http2serverConn) stopShutdownTimer()(*http2serverConn) upgradeRequest(req *Request)(*http2serverConn) vlogf(format string, args ...interface{}) called from handler goroutines. writeDataFromHandler writes DATA response frames from a handler on
the given stream. writeFrame schedules a frame to write and sends it if there's nothing
already being written.
There is no pushback here (the serve goroutine never blocks). It's
the http.Handlers that block, waiting for their previous frames to
make it onto the wire
If you're not on the serve goroutine, use writeFrameFromHandler instead. writeFrameAsync runs in its own goroutine and writes a single frame
and then reports when it's done.
At most one goroutine can be running writeFrameAsync at a time per
serverConn. writeFrameFromHandler sends wr to sc.wantWriteFrameCh, but aborts
if the connection has gone away.
This must not be run from the serve goroutine itself, else it might
deadlock writing to sc.wantWriteFrameCh (which is only mildly
buffered and is read by serve itself). If you're on the serve
goroutine, call writeFrame instead. called from handler goroutines.
h may be nil. wroteFrame is called on the serve goroutine with the result of
whatever happened on writeFrameAsync.
*http2serverConn : http2writeContext
Setting is a setting parameter: which setting it is, and its value. ID is which setting is being set.
See https://httpwg.org/specs/rfc7540.html#SettingFormat Val is the value.( http2Setting) String() string Valid reports whether the setting is valid.
http2Setting : fmt.Stringer
http2Setting : context.stringer
http2Setting : runtime.stringer
A SettingsFrame conveys configuration parameters that affect how
endpoints communicate, such as preferences and constraints on peer
behavior.
See https://httpwg.org/specs/rfc7540.html#SETTINGS Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type. Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement. StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0. Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame).http2FrameHeaderhttp2FrameHeader // caller can access []byte fields in the Framep[]byte ForeachSetting runs fn for each setting.
It stops and returns the first error. HasDuplicates reports whether f contains any duplicate setting IDs. Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.(*http2SettingsFrame) IsAck() bool(*http2SettingsFrame) NumSettings() int Setting returns the setting from the frame at the given 0-based index.
The index must be >= 0 and less than f.NumSettings().( http2SettingsFrame) String() string(*http2SettingsFrame) Value(id http2SettingID) (v uint32, ok bool)(*http2SettingsFrame) checkValid()(*http2SettingsFrame) invalidate()( http2SettingsFrame) writeDebug(buf *bytes.Buffer)
http2SettingsFrame : fmt.Stringer
*http2SettingsFrame : http2Frame
http2SettingsFrame : context.stringer
http2SettingsFrame : runtime.stringer
// owned by sorter Keys returns the sorted keys of h.
The returned slice is only valid until s used again or returned to
its pool.(*http2sorter) Len() int(*http2sorter) Less(i, j int) bool(*http2sorter) SortStrings(ss []string)(*http2sorter) Swap(i, j int)
*http2sorter : sort.Interface
( http2sortPriorityNodeSiblings) Len() int( http2sortPriorityNodeSiblings) Less(i, k int) bool( http2sortPriorityNodeSiblings) Swap(i, k int)
http2sortPriorityNodeSiblings : sort.Interface
stream represents a stream. This is the minimal metadata needed by
the serve goroutine. Most of the actual stream state is owned by
the http.Handler's goroutine in the responseWriter. Because the
responseWriter's responseWriterState is recycled at the end of a
handler, this struct intentionally has no pointer to the
*responseWriter{,State} itself, as the Handler ending nils out the
responseWriter's state field. // non-nil if expecting DATA frames owned by serverConn's serve loop: // body bytes seen so farcancelCtxfunc() // set before cw is closedctxcontext.Context // closed wait stream transitions to closed state // or -1 if undeclared // limits writing from Handler to client // HEADER frame for trailers was seeniduint32 // what the client is allowed to POST/etc to us // nil if unused // handler's Request.Trailer // RST_STREAM queued for write; set by sc.resetStream immutable:statehttp2streamState // accumulated trailers // nil if unused // whether we wrote headers (not status 100) copyTrailersToHandlerRequest is run in the Handler's goroutine in
its Request.Body.Read just before it gets io.EOF. endStream closes a Request.Body's pipe. It is called when a DATA
frame says a request body is over (or after trailers). isPushed reports whether the stream is server-initiated. onReadTimeout is run on its own goroutine (from time.AfterFunc)
when the stream's ReadTimeout has fired. onWriteTimeout is run on its own goroutine (from time.AfterFunc)
when the stream's WriteTimeout has fired.(*http2stream) processTrailerHeaders(f *http2MetaHeadersFrame) error
Transport is an HTTP/2 Transport.
A Transport internally caches connections to servers. It is safe
for concurrent use by multiple goroutines. AllowHTTP, if true, permits HTTP/2 requests using the insecure,
plain-text "http" scheme. Note that this does not enable h2c support. ConnPool optionally specifies an alternate connection pool to use.
If nil, the default is used. CountError, if non-nil, is called on HTTP/2 transport errors.
It's intended to increment a metric for monitoring, such
as an expvar or Prometheus metric.
The errType consists of only ASCII word characters. DialTLS specifies an optional dial function for creating
TLS connections for requests.
If DialTLSContext and DialTLS is nil, tls.Dial is used.
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. DialTLSContext specifies an optional dial function with context for
creating TLS connections for requests.
If DialTLSContext and DialTLS is nil, tls.Dial is used.
If the returned net.Conn has a ConnectionState method like tls.Conn,
it will be used to set http.Response.TLS. 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. MaxDecoderHeaderTableSize optionally specifies the http2
SETTINGS_HEADER_TABLE_SIZE to send in the initial settings frame. It
informs the remote endpoint of the maximum size of the header compression
table used to decode header blocks, in octets. If zero, the default value
of 4096 is used. MaxEncoderHeaderTableSize optionally specifies an upper limit for the
header compression table used for encoding request headers. Received
SETTINGS_HEADER_TABLE_SIZE settings are capped at this limit. If zero,
the default value of 4096 is used. MaxHeaderListSize is the http2 SETTINGS_MAX_HEADER_LIST_SIZE to
send in the initial settings frame. It is how many bytes
of response headers are allowed. Unlike the http2 spec, zero here
means to use a default limit (currently 10MB). If you actually
want to advertise an unlimited value to the peer, Transport
interprets the highest possible value here (0xffffffff or 1<<32-1)
to mean no limit. MaxReadFrameSize is the http2 SETTINGS_MAX_FRAME_SIZE to send in the
initial settings frame. It is the size in bytes of the largest frame
payload that the sender is willing to receive. If 0, no setting is
sent, and the value is provided by the peer, which should be 16384
according to the spec:
https://datatracker.ietf.org/doc/html/rfc7540#section-6.5.2.
Values are bounded in the range 16k to 16M. PingTimeout is the timeout after which the connection will be closed
if a response to Ping is not received.
Defaults to 15s. ReadIdleTimeout is the timeout after which a health check using ping
frame will be carried out if no frame is received on the connection.
Note that a ping response will is considered a received frame, so if
there is no other traffic on the connection, the health check will
be performed every ReadIdleTimeout interval.
If zero, no health check is performed. StrictMaxConcurrentStreams controls whether the server's
SETTINGS_MAX_CONCURRENT_STREAMS should be respected
globally. If false, new TCP connections are created to the
server as needed to keep each under the per-connection
SETTINGS_MAX_CONCURRENT_STREAMS limit. If true, the
server's SETTINGS_MAX_CONCURRENT_STREAMS is interpreted as
a global limit and callers of RoundTrip block when needed,
waiting for their turn. TLSClientConfig specifies the TLS configuration to use with
tls.Client. If nil, the default configuration is used. WriteByteTimeout is the timeout after which the connection will be
closed no data can be written to it. The timeout begins when data is
available to write, and is extended whenever any bytes are written.connPoolOncesync.Once // non-nil version of ConnPool t1, if non-nil, is the standard library Transport using
this transport. Its settings are used (but not its
RoundTrip method, etc). CloseIdleConnections closes any connections which were previously
connected from previous requests but are now sitting idle.
It does not interrupt any connections currently in use.(*http2Transport) NewClientConn(c net.Conn) (*http2ClientConn, error)(*http2Transport) RoundTrip(req *Request) (*Response, error) RoundTripOpt is like RoundTrip, but takes options.(*http2Transport) connPool() http2ClientConnPool(*http2Transport) dialClientConn(ctx context.Context, addr string, singleUse bool) (*http2ClientConn, error)(*http2Transport) dialTLS(ctx context.Context, network, addr string, tlsCfg *tls.Config) (net.Conn, error) dialTLSWithContext uses tls.Dialer, added in Go 1.15, to open a TLS
connection.(*http2Transport) disableCompression() bool disableKeepAlives reports whether connections should be closed as
soon as possible after handling the first request.(*http2Transport) expectContinueTimeout() time.Duration(*http2Transport) idleConnTimeout() time.Duration(*http2Transport) initConnPool()(*http2Transport) logf(format string, args ...interface{})(*http2Transport) maxDecoderHeaderTableSize() uint32(*http2Transport) maxEncoderHeaderTableSize() uint32(*http2Transport) maxFrameReadSize() uint32(*http2Transport) maxHeaderListSize() uint32(*http2Transport) newClientConn(c net.Conn, singleUse bool) (*http2ClientConn, error)(*http2Transport) newTLSConfig(host string) *tls.Config(*http2Transport) pingTimeout() time.Duration(*http2Transport) vlogf(format string, args ...interface{})
*http2Transport : RoundTripper
*http2Transport : h2Transport
func http2ConfigureTransports(t1 *Transport) (*http2Transport, error)
func http2configureTransports(t1 *Transport) (*http2Transport, error)
transportResponseBody is the concrete type of Transport.RoundTrip's
Response.Body. It is an io.ReadCloser.cs*http2clientStream( http2transportResponseBody) Close() error( http2transportResponseBody) Read(p []byte) (n int, err error)
http2transportResponseBody : io.Closer
http2transportResponseBody : io.ReadCloser
http2transportResponseBody : io.Reader
An UnknownFrame is the frame type returned when the frame type is unknown
or no specific frame type parser exists. Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type. Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement. StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0. Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame).http2FrameHeaderhttp2FrameHeader // caller can access []byte fields in the Framep[]byte Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface. Payload returns the frame's payload (after the header). It is not
valid to call this method after a subsequent call to
Framer.ReadFrame, nor is it valid to retain the returned slice.
The memory is owned by the Framer and is invalidated when the next
frame is read.( http2UnknownFrame) String() string(*http2UnknownFrame) checkValid()(*http2UnknownFrame) invalidate()( http2UnknownFrame) writeDebug(buf *bytes.Buffer)
http2UnknownFrame : fmt.Stringer
*http2UnknownFrame : http2Frame
http2UnknownFrame : context.stringer
http2UnknownFrame : runtime.stringer
A WindowUpdateFrame is used to implement flow control.
See https://httpwg.org/specs/rfc7540.html#rfc.section.6.9 Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type. Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement. StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0. Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame). // never read with high bit sethttp2FrameHeaderhttp2FrameHeader // caller can access []byte fields in the Frame Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.( http2WindowUpdateFrame) String() string(*http2WindowUpdateFrame) checkValid()(*http2WindowUpdateFrame) invalidate()( http2WindowUpdateFrame) writeDebug(buf *bytes.Buffer)
http2WindowUpdateFrame : fmt.Stringer
*http2WindowUpdateFrame : http2Frame
http2WindowUpdateFrame : context.stringer
http2WindowUpdateFrame : runtime.stringer
writeContext is the interface needed by the various frame writer
types below. All the writeFrame methods below are scheduled via the
frame writing scheduler (see writeScheduler in writesched.go).
This interface is implemented by *serverConn.
TODO: decide whether to a) use this in the client code (which didn't
end up using this yet, because it has a simpler design, not
currently implementing priorities), or b) delete this and
make the server code a bit more concrete.( http2writeContext) CloseConn() error( http2writeContext) Flush() error( http2writeContext) Framer() *http2Framer HeaderEncoder returns an HPACK encoder that writes to the
returned buffer.
*http2serverConn
func http2splitHeaderBlock(ctx http2writeContext, headerBlock []byte, fn func(ctx http2writeContext, frag []byte, firstFrag, lastFrag bool) error) error
writePushPromise is a request to write a PUSH_PROMISE and 0+ CONTINUATION frames. Creates an ID for a pushed stream. This runs on serveG just before
the frame is written. The returned ID is copied to promisedID.hHeader // for :methodpromisedIDuint32 // pusher stream // for :scheme, :authority, :path(*http2writePushPromise) staysWithinBuffer(max int) bool(*http2writePushPromise) writeFrame(ctx http2writeContext) error(*http2writePushPromise) writeHeaderBlock(ctx http2writeContext, frag []byte, firstFrag, lastFrag bool) error
*http2writePushPromise : http2writeFramer
writeQueue is used by implementations of WriteScheduler.next*http2writeQueueprev*http2writeQueues[]http2FrameWriteRequest consume consumes up to n bytes from q.s[0]. If the frame is
entirely consumed, it is removed from the queue. If the frame
is partially consumed, the frame is kept with the consumed
bytes removed. Returns true iff any bytes were consumed.(*http2writeQueue) empty() bool(*http2writeQueue) push(wr http2FrameWriteRequest)(*http2writeQueue) shift() http2FrameWriteRequest
get returns an empty writeQueue. put inserts an unused writeQueue into the pool.
WriteScheduler is the interface implemented by HTTP/2 write schedulers.
Methods are never called concurrently. AdjustStream adjusts the priority of the given stream. This may be called
on a stream that has not yet been opened or has been closed. Note that
RFC 7540 allows PRIORITY frames to be sent on streams in any state. See:
https://tools.ietf.org/html/rfc7540#section-5.1 CloseStream closes a stream in the write scheduler. Any frames queued on
this stream should be discarded. It is illegal to call this on a stream
that is not open -- the call may panic. OpenStream opens a new stream in the write scheduler.
It is illegal to call this with streamID=0 or with a streamID that is
already open -- the call may panic. Pop dequeues the next frame to write. Returns false if no frames can
be written. Frames with a given wr.StreamID() are Pop'd in the same
order they are Push'd, except RST_STREAM frames. No frames should be
discarded except by CloseStream. Push queues a frame in the scheduler. In most cases, this will not be
called with wr.StreamID()!=0 unless that stream is currently open. The one
exception is RST_STREAM frames, which may be sent on idle or closed streams.
*http2priorityWriteScheduler
*http2randomWriteScheduler
*http2roundRobinWriteScheduler
func http2NewPriorityWriteScheduler(cfg *http2PriorityWriteSchedulerConfig) http2WriteScheduler
func http2NewRandomWriteScheduler() http2WriteScheduler
func http2newRoundRobinWriteScheduler() http2WriteScheduler
incomparable is a zero-width, non-comparable type. Adding it to a struct
makes that struct also non-comparable, and generally doesn't add
any size (as long as it's first).
initALPNRequest is an HTTP handler that initializes certain
uninitialized fields in its *Request. Such partially-initialized
Requests come from ALPN protocol handlers.c*tls.Connctxcontext.ContexthserverHandler BaseContext is an exported but unadvertised http.Handler method
recognized by x/net/http2 to pass down a context; the TLSNextProto
API predates context support so we shoehorn through the only
interface we have available.( initALPNRequest) ServeHTTP(rw ResponseWriter, req *Request)
initALPNRequest : Handler
loggingConn is used for debugging.Connnet.Connnamestring(*loggingConn) Close() (err error) LocalAddr returns the local network address, if known.(*loggingConn) Read(p []byte) (n int, err error) RemoteAddr returns the remote network address, if known. SetDeadline sets the read and write deadlines associated
with the connection. It is equivalent to calling both
SetReadDeadline and SetWriteDeadline.
A deadline is an absolute time after which I/O operations
fail instead of blocking. The deadline applies to all future
and pending I/O, not just the immediately following call to
Read or Write. After a deadline has been exceeded, the
connection can be refreshed by setting a deadline in the future.
If the deadline is exceeded a call to Read or Write or to other
I/O methods will return an error that wraps os.ErrDeadlineExceeded.
This can be tested using errors.Is(err, os.ErrDeadlineExceeded).
The error's Timeout method will return true, but note that there
are other possible errors for which the Timeout method will
return true even if the deadline has not been exceeded.
An idle timeout can be implemented by repeatedly extending
the deadline after successful Read or Write calls.
A zero value for t means I/O operations will not time out. SetReadDeadline sets the deadline for future Read calls
and any currently-blocked Read call.
A zero value for t means Read will not time out. SetWriteDeadline sets the deadline for future Write calls
and any currently-blocked Write call.
Even if write times out, it may return n > 0, indicating that
some of the data was successfully written.
A zero value for t means Write will not time out.(*loggingConn) Write(p []byte) (n int, err error)
*loggingConn : net.Conn
*loggingConn : internal/bisect.Writer
*loggingConn : io.Closer
*loggingConn : io.ReadCloser
*loggingConn : io.Reader
*loggingConn : io.ReadWriteCloser
*loggingConn : io.ReadWriter
*loggingConn : io.WriteCloser
*loggingConn : io.Writer
*loggingConn : crypto/tls.transcriptHash
nothingWrittenError wraps a write errors which ended up writing zero bytes.errorerror( nothingWrittenError) Error() builtin.string( nothingWrittenError) Unwrap() error
nothingWrittenError : error
nothingWrittenError : github.com/go-faster/errors.Wrapper
onceCloseListener wraps a net.Listener, protecting it from
multiple Close calls.Listenernet.ListenercloseErrerroroncesync.Once Accept waits for and returns the next connection to the listener. Addr returns the listener's network address.(*onceCloseListener) Close() error(*onceCloseListener) close()
*onceCloseListener : net.Listener
*onceCloseListener : io.Closer
persistConn wraps a connection, usually a persistent one
(but may be used for non-keep-alive requests as well) alt optionally specifies the TLS NextProto RoundTripper.
This is used for HTTP/2 today and future protocols later.
If it's non-nil, the rest of the fields are unused. // from conn // an error has happened on this connection; marked broken so it's not reused. // to conncacheKeyconnectMethodKey // set non-nil if conn is canceled // closed when conn closed // set non-nil when conn is closed, before closech is closedconnnet.Conn Both guarded by Transport.idleMu: // time it last become idle // holding an AfterFunc to close itisProxybool // guards following fields mutateHeaderFunc is an optional func to modify extra
headers on each outbound request before it's written. (the
original Request given to RoundTrip is not modified)numExpectedResponsesint // bytes written // bytes allowed to be read; owned by readLoop // written by roundTrip; read by readLoop // whether conn has had successful request/response and is being reused. // whether we've seen EOF from conn; owned by readLoopt*TransporttlsState*tls.ConnectionState writeErrCh passes the request write error (usually nil)
from the writeLoop goroutine to the readLoop which passes
it off to the res.Body reader, which then uses it to decide
whether or not a connection can be reused. Issue 7569. // closed when write loop ends // written by roundTrip; read by writeLoop(*persistConn) Read(p []byte) (n int, err error) Add TLS to a persistent connection, i.e. negotiate a TLS session. If pconn is already a TLS
tunnel, this function establishes a nested TLS session inside the encrypted channel.
The remote endpoint's name may be overridden by TLSClientConfig.ServerName.(*persistConn) cancelRequest(err error) canceled returns non-nil if the connection was closed due to
CancelRequest or due to context cancellation. close closes the underlying TCP connection and closes
the pc.closech channel.
The provided err is only for testing and debugging; in normal
circumstances it should never be seen by users. closeConnIfStillIdle closes the connection if it's still sitting idle.
This is what's called by the persistConn's idleTimer, and is run in its
own goroutine.(*persistConn) closeLocked(err error)(*persistConn) gotIdleConnTrace(idleAt time.Time) (t httptrace.GotConnInfo) isBroken reports whether this connection is in a known broken state. isReused reports whether this connection has been used before. mapRoundTripError returns the appropriate error value for
persistConn.roundTrip.
The provided err is the first error that (*persistConn).roundTrip
happened to receive from its select statement.
The startBytesWritten value should be the value of pc.nwrite before the roundTrip
started writing the request. markReused marks this connection as having been successfully used for a
request and response.(*persistConn) maxHeaderResponseSize() int64(*persistConn) readLoop()(*persistConn) readLoopPeekFailLocked(peekErr error) readResponse reads an HTTP response (or two, in the case of "Expect:
100-continue") from the server. It returns the final non-100 one.
trace is optional.(*persistConn) roundTrip(req *transportRequest) (resp *Response, err error) shouldRetryRequest reports whether we should retry sending a failed
HTTP request on a new connection. The non-nil input error is the
error from roundTrip. waitForContinue returns the function to block until
any response, timeout or connection close. After any of them,
the function returns a bool which indicates if the body should be sent.(*persistConn) writeLoop() wroteRequest is a check before recycling a connection that the previous write
(from writeLoop above) happened and was successful.
*persistConn : io.Reader
func (*Transport).dialConn(ctx context.Context, cm connectMethod) (pconn *persistConn, err error)
func (*Transport).getConn(treq *transportRequest, cm connectMethod) (pc *persistConn, err error)
func (*Transport).putOrCloseIdleConn(pconn *persistConn)
func (*Transport).removeIdleConn(pconn *persistConn) bool
func (*Transport).removeIdleConnLocked(pconn *persistConn) bool
func (*Transport).tryPutIdleConn(pconn *persistConn) error
persistConnWriter is the io.Writer written to by pc.bw.
It accumulates the number of bytes written to the underlying conn,
so the retry logic can determine whether any bytes made it across
the wire.
This is exactly 1 pointer field wide so it can go into an interface
without allocation.pc*persistConn ReadFrom exposes persistConnWriter's underlying Conn to io.Copy and if
the Conn implements io.ReaderFrom, it can take advantage of optimizations
such as sendfile.( persistConnWriter) Write(p []byte) (n int, err error)
persistConnWriter : internal/bisect.Writer
persistConnWriter : io.ReaderFrom
persistConnWriter : io.Writer
persistConnWriter : crypto/tls.transcriptHash
readWriteCloserBody is the Response.Body type used when we want to
give users write access to the Body through the underlying
connection (TCP, unless using custom dialers). This is then
the concrete type for a Response.Body on the 101 Switching
Protocols response, as used by WebSockets, h2c, etc.ReadWriteCloserio.ReadWriteCloser // used until empty( readWriteCloserBody) Close() error(*readWriteCloserBody) Read(p []byte) (n int, err error)( readWriteCloserBody) Write([]byte) (int, error)
readWriteCloserBody : internal/bisect.Writer
readWriteCloserBody : io.Closer
*readWriteCloserBody : io.ReadCloser
*readWriteCloserBody : io.Reader
*readWriteCloserBody : io.ReadWriteCloser
*readWriteCloserBody : io.ReadWriter
readWriteCloserBody : io.WriteCloser
readWriteCloserBody : io.Writer
readWriteCloserBody : crypto/tls.transcriptHash
whether the Transport (as opposed to the user client code)
added the Accept-Encoding gzip header. If the Transport
set it, only then do we transparently decode the gzip. // closed when roundTrip caller has returnedcancelKeycancelKey // unbuffered; always send in select on callerGone Optional blocking chan for Expect: 100-continue (for send).
If the request has an "Expect: 100-continue" header and
the server responds 100 Continue, readLoop send a value
to writeLoop via this chan.req*Request
requestBodyReadError wraps an error from (*Request).write to indicate
that the error came from a Read call on the Request.Body.
This error type should not escape the net/http package to users.errorerror( requestBodyReadError) Error() builtin.string
requestBodyReadError : error
A response represents the server side of an HTTP response. // handler accessed handlerHeader via Header canWriteContinue is an atomic boolean that says whether or
not a 100 Continue header can be written to the
connection.
writeContinueMu must be held while writing the header.
These two fields together synchronize the body reader (the
expectContinueReader, which wants to write 100 Continue)
against the main writer. // when ServeHTTP exitsclenBuf[10]byte close connection after this reply. set on request and
updated after response from handler if there's a
"Connection: keep-alive" response header and a
Content-Length. closeNotifyCh is the channel returned by CloseNotify.
TODO(bradfitz): this is currently (for Go 1.8) always
non-nil. Make this lazily-created again as it used to be?conn*conn // explicitly-declared Content-Length; or -1cwchunkWriter Buffers for Date, Content-Length, and status code // atomic (only false->true winner should send) When fullDuplex is false (the default), we consume any remaining
request body before starting to write a response. // set true when the handler exits handlerHeader is the Header that Handlers get access to,
which may be retained and mutated even after WriteHeader.
handlerHeader is copied into cw.header at WriteHeader
time, and privately mutated thereafter. // request for this responsereqBodyio.ReadCloser requestBodyLimitHit is set by requestTooLarge when
maxBytesReader hits its max size. It is checked in
WriteHeader, to make sure we don't consume the
remaining request body to try to advance to the next HTTP
request. Instead, when this is set, we stop reading
subsequent requests on this connection and stop reading
input from it. // status code passed to WriteHeaderstatusBuf[3]byte trailers are the headers to be sent after the handler
finishes writing the body. This field is initialized from
the Trailer response header when the response header is
written. // buffers output in chunks to chunkWriter // HTTP/1.0 w/ Connection "keep-alive" // HTTP request has Connection "close"writeContinueMusync.Mutex // number of bytes written in body // 100 Continue response was written // a non-1xx header has been (logically) written(*response) CloseNotify() <-chan bool(*response) EnableFullDuplex() error(*response) Flush()(*response) FlushError() error(*response) Header() Header Hijack implements the Hijacker.Hijack method. Our response is both a ResponseWriter
and a Hijacker. ReadFrom is here to optimize copying from an *os.File regular file
to a *net.TCPConn with sendfile, or from a supported src type such
as a *net.TCPConn on Linux with splice.(*response) SetReadDeadline(deadline time.Time) error(*response) SetWriteDeadline(deadline time.Time) error The Life Of A Write is like this:
Handler starts. No header has been sent. The handler can either
write a header, or just start writing. Writing before sending a header
sends an implicitly empty 200 OK header.
If the handler didn't declare a Content-Length up front, we either
go into chunking mode or, if the handler finishes running before
the chunking buffer size, we compute a Content-Length and send that
in the header instead.
Likewise, if the handler didn't set a Content-Type, we sniff that
from the initial chunk of output.
The Writers are wired together like:
1. *response (the ResponseWriter) ->
2. (*response).w, a *bufio.Writer of bufferBeforeChunkingSize bytes ->
3. chunkWriter.Writer (whose writeHeader finalizes Content-Length/Type)
and which writes the chunk headers, if needed ->
4. conn.bufw, a *bufio.Writer of default (4kB) bytes, writing to ->
5. checkConnErrorWriter{c}, which notes any non-nil error on Write
and populates c.werr with it if so, but otherwise writes to ->
6. the rwc, the net.Conn.
TODO(bradfitz): short-circuit some of the buffering when the
initial header contains both a Content-Type and Content-Length.
Also short-circuit in (1) when the header's been sent and not in
chunking mode, writing directly to (4) instead, if (2) has no
buffered data. More generally, we could short-circuit from (1) to
(3) even in chunking mode if the write size from (1) is over some
threshold and nothing is in (2). The answer might be mostly making
bufferBeforeChunkingSize smaller and having bufio's fast-paths deal
with this instead.(*response) WriteHeader(code int)(*response) WriteString(data string) (n int, err error) bodyAllowed reports whether a Write is allowed for this response type.
It's illegal to call this before the header has been flushed.(*response) closedRequestBodyEarly() bool declareTrailer is called for each Trailer header when the
response header is written. It notes that a header will need to be
written in the trailers at the end of the response. finalTrailers is called after the Handler exits and returns a non-nil
value if the Handler set any trailers.(*response) finishRequest() requestTooLarge is called by maxBytesReader when too much input has
been read from the client.(*response) sendExpectationFailed() shouldReuseConnection reports whether the underlying TCP connection can be reused.
It must only be called after the handler is done executing. either dataB or dataS is non-zero.
*response : CloseNotifier
*response : Flusher
*response : Hijacker
*response : ResponseWriter
*response : internal/bisect.Writer
*response : io.ReaderFrom
*response : io.StringWriter
*response : io.Writer
*response : http2stringWriter
*response : crypto/tls.transcriptHash
responseAndError is how the goroutine reading from an HTTP/1 server
communicates with the goroutine doing the RoundTrip.errerror // else use this response (see res method)
serverHandler delegates to either the server's Handler or
DefaultServeMux and also handles "OPTIONS *" requests.srv*Server( serverHandler) ServeHTTP(rw ResponseWriter, req *Request)
serverHandler : Handler
An Addr represents a SOCKS-specific address.
Either Name or IP is used exclusively.IPnet.IP // fully-qualified domain namePortint(*socksAddr) Network() string(*socksAddr) String() string
*socksAddr : net.Addr
*socksAddr : fmt.Stringer
*socksAddr : context.stringer
*socksAddr : runtime.stringer
A Conn represents a forward proxy connection.Connnet.ConnboundAddrnet.Addr BoundAddr returns the address assigned by the proxy server for
connecting to the command target address from the proxy server. Close closes the connection.
Any blocked Read or Write operations will be unblocked and return errors. LocalAddr returns the local network address, if known. Read reads data from the connection.
Read can be made to time out and return an error after a fixed
time limit; see SetDeadline and SetReadDeadline. RemoteAddr returns the remote network address, if known. SetDeadline sets the read and write deadlines associated
with the connection. It is equivalent to calling both
SetReadDeadline and SetWriteDeadline.
A deadline is an absolute time after which I/O operations
fail instead of blocking. The deadline applies to all future
and pending I/O, not just the immediately following call to
Read or Write. After a deadline has been exceeded, the
connection can be refreshed by setting a deadline in the future.
If the deadline is exceeded a call to Read or Write or to other
I/O methods will return an error that wraps os.ErrDeadlineExceeded.
This can be tested using errors.Is(err, os.ErrDeadlineExceeded).
The error's Timeout method will return true, but note that there
are other possible errors for which the Timeout method will
return true even if the deadline has not been exceeded.
An idle timeout can be implemented by repeatedly extending
the deadline after successful Read or Write calls.
A zero value for t means I/O operations will not time out. SetReadDeadline sets the deadline for future Read calls
and any currently-blocked Read call.
A zero value for t means Read will not time out. SetWriteDeadline sets the deadline for future Write calls
and any currently-blocked Write call.
Even if write times out, it may return n > 0, indicating that
some of the data was successfully written.
A zero value for t means Write will not time out. Write writes data to the connection.
Write can be made to time out and return an error after a fixed
time limit; see SetDeadline and SetWriteDeadline.
socksConn : net.Conn
socksConn : internal/bisect.Writer
socksConn : io.Closer
socksConn : io.ReadCloser
socksConn : io.Reader
socksConn : io.ReadWriteCloser
socksConn : io.ReadWriter
socksConn : io.WriteCloser
socksConn : io.Writer
socksConn : crypto/tls.transcriptHash
A Dialer holds SOCKS-specific options. AuthMethods specifies the list of request authentication
methods.
If empty, SOCKS client requests only AuthMethodNotRequired. Authenticate specifies the optional authentication
function. It must be non-nil when AuthMethods is not empty.
It must return an error when the authentication is failed. ProxyDial specifies the optional dial function for
establishing the transport connection. // either CmdConnect or cmdBind // proxy server address // network between a proxy server and a client Dial connects to the provided address on the provided network.
Unlike DialContext, it returns a raw transport connection instead
of a forward proxy connection.
Deprecated: Use DialContext or DialWithConn instead. DialContext connects to the provided address on the provided
network.
The returned error value may be a net.OpError. When the Op field of
net.OpError contains "socks", the Source field contains a proxy
server address and the Addr field contains a command target
address.
See func Dial of the net package of standard library for a
description of the network and address parameters. DialWithConn initiates a connection from SOCKS server to the target
network and address using the connection c that is already
connected to the SOCKS server.
It returns the connection's local address assigned by the SOCKS
server.(*socksDialer) connect(ctx context.Context, c net.Conn, address string) (_ net.Addr, ctxErr error)(*socksDialer) pathAddrs(address string) (proxy, dst net.Addr, err error)(*socksDialer) validateTarget(network, address string) error
*socksDialer : golang.org/x/net/proxy.ContextDialer
*socksDialer : golang.org/x/net/proxy.Dialer
func socksNewDialer(network, address string) *socksDialer
UsernamePassword are the credentials for the username/password
authentication method.PasswordstringUsernamestring Authenticate authenticates a pair of username and password with the
proxy server.
statusError is an error used to respond to a request with an HTTP status.
The text should be plain text without user info or other embedded errors.codeinttextstring( statusError) Error() string
statusError : error
transferWriter inspects the fields of a user-supplied Request or Response,
sanitizes them without changing the user object and provides methods for
writing the respective header, body and trailer in wire format.Bodyio.ReaderBodyCloserio.Closer // non-nil if probeRequestBody calledClosebool // -1 means unknown, 0 means exactly none // flush headers to network before bodyHeaderHeaderIsResponseboolMethodstringResponseToHEADboolTrailerHeaderTransferEncoding[]string // any non-EOF error from reading Body doBodyCopy wraps a copy operation, with any resulting error also
being saved in bodyReadError.
This function is only intended for use in writeBody. probeRequestBody reads a byte from t.Body to see whether it's empty
(returns io.EOF right away).
But because we've had problems with this blocking users in the past
(issue 17480) when the body is a pipe (perhaps waiting on the response
headers before the pipe is fed data), we need to be careful and bound how
long we wait for it. This delay will only affect users if all the following
are true:
- the request body blocks
- the content length is not set (or set to -1)
- the method doesn't usually have a body (GET, HEAD, DELETE, ...)
- there is no transfer-encoding=chunked already set.
In other words, this delay will not normally affect anybody, and there
are workarounds if it does. shouldSendChunkedRequestBody reports whether we should try to send a
chunked request body to the server. In particular, the case we really
want to prevent is sending a GET or other typically-bodyless request to a
server with a chunked body when the body has zero bytes, since GETs with
bodies (while acceptable according to specs), even zero-byte chunked
bodies, are approximately never seen in the wild and confuse most
servers. See Issue 18257, as one example.
The only reason we'd send such a request is if the user set the Body to a
non-nil value (say, io.NopCloser(bytes.NewReader(nil))) and didn't
set ContentLength, or NewRequest set it to -1 (unknown), so then we assume
there's bytes to send.
This code tries to read a byte from the Request.Body in such cases to see
whether the body actually has content (super rare) or is actually just
a non-nil content-less ReadCloser (the more common case). In that more
common case, we act as if their Body were nil instead, and don't send
a body.(*transferWriter) shouldSendContentLength() bool unwrapBody unwraps the body's inner reader if it's a
nopCloser. This is to ensure that body writes sourced from local
files (*os.File types) are properly optimized.
This function is only intended for use in writeBody. always closes t.BodyCloser(*transferWriter) writeHeader(w io.Writer, trace *httptrace.ClientTrace) error
func newTransferWriter(r any) (t *transferWriter, err error)
transportReadFromServerError is used by Transport.readLoop when the
1 byte peek read fails and we're actually anticipating a response.
Usually this is just due to the inherent keep-alive shut down race,
where the server closed the connection at the same time the client
wrote. The underlying err field is usually io.EOF or some
ECONNRESET sort of thing which varies by platform. But it might be
the user's custom net.Conn.Read error too, so we carry it along for
them to return from Transport.RoundTrip.errerror( transportReadFromServerError) Error() string( transportReadFromServerError) Unwrap() error
transportReadFromServerError : error
transportReadFromServerError : github.com/go-faster/errors.Wrapper
transportRequest is a wrapper around a *Request that adds
optional extra headers to write and stores any error to return
from roundTrip. // original request, not to be mutated 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. 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. 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. 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. 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. 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. 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. For server requests, Host specifies the host on which the
URL is sought. For HTTP/1 (per RFC 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. Method specifies the HTTP method (GET, POST, PUT, etc.).
For client requests, an empty string means GET.
Go's HTTP client does not support sending a request with
the CONNECT method. See the documentation on Transport for
details. 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. 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. 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. // "HTTP/1.0" // 1 // 0 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. 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. Response is the redirect response which caused this request
to be created. This field is only populated during client
redirects. 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. 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. 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. 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. (See RFC 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.cancelKeycancelKey // first setError value for mapRoundTripError to consider // extra headers to write, or nil // guards err ctx is either the client or server context. It should only
be modified via copying the whole Request using Clone or WithContext.
It is unexported to prevent people from using Context wrong
and mutating the contexts held by callers of the same request. // optional AddCookie adds a cookie to the request. Per RFC 6265 section 5.4,
AddCookie does not attach more than one Cookie header field. That
means all cookies, if any, are written into the same line,
separated by semicolon.
AddCookie only sanitizes c's name and value, and does not sanitize
a Cookie header already present in the request. BasicAuth returns the username and password provided in the request's
Authorization header, if the request uses HTTP Basic Authentication.
See RFC 2617, Section 2. Clone returns a deep copy of r with its context changed to ctx.
The provided ctx must be non-nil.
For an outgoing client request, the context controls the entire
lifetime of a request and its response: obtaining a connection,
sending the request, and reading the response headers and body. Context returns the request's context. To change the context, use
Clone or WithContext.
The returned context is always non-nil; it defaults to the
background context.
For outgoing client requests, the context controls cancellation.
For incoming server requests, the context is canceled when the
client's connection closes, the request is canceled (with HTTP/2),
or when the ServeHTTP method returns. Cookie returns the named cookie provided in the request or
ErrNoCookie if not found.
If multiple cookies match the given name, only one cookie will
be returned. Cookies parses and returns the HTTP cookies sent with the request. FormFile returns the first file for the provided form key.
FormFile calls ParseMultipartForm and ParseForm if necessary. FormValue returns the first value for the named component of the query.
POST and PUT body parameters take precedence over URL query string values.
FormValue calls ParseMultipartForm and ParseForm if necessary and ignores
any errors returned by these functions.
If key is not present, FormValue returns the empty string.
To access multiple values of the same key, call ParseForm and
then inspect Request.Form directly. MultipartReader returns a MIME multipart reader if this is a
multipart/form-data or a multipart/mixed POST request, else returns nil and an error.
Use this function instead of ParseMultipartForm to
process the request body as a stream. ParseForm populates r.Form and r.PostForm.
For all requests, ParseForm parses the raw query from the URL and updates
r.Form.
For POST, PUT, and PATCH requests, it also reads the request body, parses it
as a form and puts the results into both r.PostForm and r.Form. Request body
parameters take precedence over URL query string values in r.Form.
If the request Body's size has not already been limited by MaxBytesReader,
the size is capped at 10MB.
For other HTTP methods, or when the Content-Type is not
application/x-www-form-urlencoded, the request Body is not read, and
r.PostForm is initialized to a non-nil, empty value.
ParseMultipartForm calls ParseForm automatically.
ParseForm is idempotent. ParseMultipartForm parses a request body as multipart/form-data.
The whole request body is parsed and up to a total of maxMemory bytes of
its file parts are stored in memory, with the remainder stored on
disk in temporary files.
ParseMultipartForm calls ParseForm if necessary.
If ParseForm returns an error, ParseMultipartForm returns it but also
continues parsing the request body.
After one call to ParseMultipartForm, subsequent calls have no effect. PostFormValue returns the first value for the named component of the POST,
PATCH, or PUT request body. URL query parameters are ignored.
PostFormValue calls ParseMultipartForm and ParseForm if necessary and ignores
any errors returned by these functions.
If key is not present, PostFormValue returns the empty string. ProtoAtLeast reports whether the HTTP protocol used
in the request is at least major.minor. Referer returns the referring URL, if sent in the request.
Referer is misspelled as in the request itself, a mistake from the
earliest days of HTTP. This value can also be fetched from the
Header map as Header["Referer"]; the benefit of making it available
as a method is that the compiler can diagnose programs that use the
alternate (correct English) spelling req.Referrer() but cannot
diagnose programs that use Header["Referrer"]. SetBasicAuth sets the request's Authorization header to use HTTP
Basic Authentication with the provided username and password.
With HTTP Basic Authentication the provided username and password
are not encrypted. It should generally only be used in an HTTPS
request.
The username may not contain a colon. Some protocols may impose
additional requirements on pre-escaping the username and
password. For instance, when used with OAuth2, both arguments must
be URL encoded first with url.QueryEscape. UserAgent returns the client's User-Agent, if sent in the request. WithContext returns a shallow copy of r with its context changed
to ctx. The provided ctx must be non-nil.
For outgoing client request, the context controls the entire
lifetime of a request and its response: obtaining a connection,
sending the request, and reading the response headers and body.
To create a new request with a context, use NewRequestWithContext.
To make a deep copy of a request with a new context, use Request.Clone. Write writes an HTTP/1.1 request, which is the header and body, in wire format.
This method consults the following fields of the request:
Host
URL
Method (defaults to "GET")
Header
ContentLength
TransferEncoding
Body
If Body is present, Content-Length is <= 0 and TransferEncoding
hasn't been set to "identity", Write adds "Transfer-Encoding:
chunked" to the header. Body is closed after it is sent. WriteProxy is like Write but writes the request in the form
expected by an HTTP proxy. In particular, WriteProxy writes the
initial Request-URI line of the request with an absolute URI, per
section 5.3 of RFC 7230, including the scheme and host.
In either case, WriteProxy also writes a Host header, using
either r.Host or r.URL.Host.( transportRequest) closeBody() error( transportRequest) expectsContinue() bool(*transportRequest) extraHeaders() Header isH2Upgrade reports whether r represents the http2 "client preface"
magic string.( transportRequest) isReplayable() bool(*transportRequest) logf(format string, args ...any)( transportRequest) multipartReader(allowMixed bool) (*multipart.Reader, error) outgoingLength reports the Content-Length of this outgoing (Client) request.
It maps 0 into -1 (unknown) when the Body is non-nil. requiresHTTP1 reports whether this request requires being sent on
an HTTP/1 connection.(*transportRequest) setError(err error)( transportRequest) wantsClose() bool( transportRequest) wantsHttp10KeepAlive() bool extraHeaders may be nil
waitForContinue may be nil
always closes body
func (*Transport).connectMethodForRequest(treq *transportRequest) (cm connectMethod, err error)
func (*Transport).getConn(treq *transportRequest, cm connectMethod) (pc *persistConn, err error)
A wantConn records state about a wanted connection
(that is, an active call to getConn).
The conn may be gotten by dialing or by finding an idle connection,
or a cancellation may make the conn no longer wanted.
These three options are racing against each other and use
wantConn to coordinate and agree about the winning outcome.afterDialfunc() hooks for testing to know when dials are done
beforeDial is called in the getConn goroutine when the dial is queued.
afterDial is called when the dial is completed or canceled.cmconnectMethod // context for dialerrerror // cm.key() // protects pc, err, close(ready)pc*persistConn // closed when pc, err pair is delivered cancel marks w as no longer wanting a result (for example, due to cancellation).
If a connection has been delivered already, cancel returns it with t.putOrCloseIdleConn. tryDeliver attempts to deliver pc, err to w and reports whether it succeeded. waiting reports whether w is still waiting for an answer (connection or error).
func (*Transport).dialConnFor(w *wantConn)
func (*Transport).queueForDial(w *wantConn)
func (*Transport).queueForIdleConn(w *wantConn) (delivered bool)
A wantConnQueue is a queue of wantConns. This is a queue, not a deque.
It is split into two stages - head[headPos:] and tail.
popFront is trivial (headPos++) on the first stage, and
pushBack is trivial (append) on the second stage.
If the first stage is empty, popFront can swap the
first and second stages to remedy the situation.
This two-stage split is analogous to the use of two lists
in Okasaki's purely functional queue but without the
overhead of reversing the list when swapping stages.headPosinttail[]*wantConn cleanFront pops any wantConns that are no longer waiting from the head of the
queue, reporting whether any were popped. len returns the number of items in the queue. peekFront returns the wantConn at the front of the queue without removing it. popFront removes and returns the wantConn at the front of the queue. pushBack adds w to the back of the queue.
A writeRequest is sent by the caller's goroutine to the
writeLoop's goroutine to write a request while the read loop
concurrently waits on both the write response and the server's
reply.chchan<- error Optional blocking chan for Expect: 100-continue (for receive).
If not nil, writeLoop blocks sending request body until
it receives from this chan.req*transportRequest
Package-Level Functions (total 266, in which 39 are exported)
AllowQuerySemicolons returns a handler that serves requests by converting any
unescaped 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 both
semicolons and ampersands. (See golang.org/issue/25192). Note that this
behavior doesn't match that of many proxies, and the mismatch can lead to
security issues.
AllowQuerySemicolons should be invoked before Request.ParseForm is called.
CanonicalHeaderKey returns the canonical format of the
header key s. The canonicalization converts the first
letter and any letter following a hyphen to upper case;
the rest are converted to lowercase. For example, the
canonical key for "accept-encoding" is "Accept-Encoding".
If s contains a space or invalid header field bytes, it is
returned without modifications.
DetectContentType implements the algorithm described
at https://mimesniff.spec.whatwg.org/ to determine the
Content-Type of the given data. It considers at most the
first 512 bytes of data. DetectContentType always returns
a valid MIME type: if it cannot determine a more specific one, it
returns "application/octet-stream".
Error replies to the request with the specified error message and HTTP code.
It does not otherwise end the request; the caller should ensure no further
writes are done to w.
The error message should be plain text.
FileServer returns a handler that serves HTTP requests
with the contents of the file system rooted at root.
As a special case, the returned file server redirects any request
ending in "/index.html" to the same path, without the final
"index.html".
To use the operating system's file system implementation,
use http.Dir:
http.Handle("/", http.FileServer(http.Dir("/tmp")))
To use an fs.FS implementation, use http.FS to convert it:
http.Handle("/", http.FileServer(http.FS(fsys)))
FS converts fsys to a FileSystem implementation,
for use with FileServer and NewFileTransport.
The files provided by fsys must implement io.Seeker.
Get issues a GET to the specified URL. If the response is one of
the following redirect codes, Get follows the redirect, up to a
maximum of 10 redirects:
301 (Moved Permanently)
302 (Found)
303 (See Other)
307 (Temporary Redirect)
308 (Permanent Redirect)
An error is returned if there were too many redirects or if there
was an HTTP protocol error. A non-2xx response doesn't cause an
error. Any returned error will be of type *url.Error. The url.Error
value's Timeout method will report true if 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, use NewRequest and
DefaultClient.Do.
To make a request with a specified context.Context, use NewRequestWithContext
and DefaultClient.Do.
Handle registers the handler for the given pattern
in the DefaultServeMux.
The documentation for ServeMux explains how patterns are matched.
HandleFunc registers the handler function for the given pattern
in the DefaultServeMux.
The documentation for ServeMux explains how patterns are matched.
Head issues a HEAD to the specified URL. If the response is one of
the following redirect codes, Head follows the redirect, up to a
maximum of 10 redirects:
301 (Moved Permanently)
302 (Found)
303 (See Other)
307 (Temporary Redirect)
308 (Permanent Redirect)
Head is a wrapper around DefaultClient.Head.
To make a request with a specified context.Context, use NewRequestWithContext
and DefaultClient.Do.
ListenAndServe listens on the TCP network address addr and then calls
Serve with handler to handle requests on incoming connections.
Accepted connections are configured to enable TCP keep-alives.
The handler is typically nil, in which case the DefaultServeMux is used.
ListenAndServe always returns a non-nil error.
ListenAndServeTLS acts identically to ListenAndServe, except that it
expects HTTPS connections. Additionally, files containing a certificate and
matching private key for the server must be provided. If the certificate
is signed by a certificate authority, the certFile should be the concatenation
of the server's certificate, any intermediates, and the CA's certificate.
MaxBytesHandler returns a Handler that runs h with its ResponseWriter and Request.Body wrapped by a MaxBytesReader.
MaxBytesReader is similar to io.LimitReader but is intended for
limiting the size of incoming request bodies. In contrast to
io.LimitReader, MaxBytesReader's result is a ReadCloser, returns a
non-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 maliciously
sending a large request and wasting server resources. If possible,
it tells the ResponseWriter to close the connection after the limit
has been reached.
NewFileTransport returns a new RoundTripper, serving the provided
FileSystem. The returned RoundTripper ignores the URL host in its
incoming requests, as well as most other properties of the
request.
The typical use case for NewFileTransport is to register the "file"
protocol with a Transport, as in:
t := &http.Transport{}
t.RegisterProtocol("file", http.NewFileTransport(http.Dir("/")))
c := &http.Client{Transport: t}
res, err := c.Get("file:///etc/passwd")
...
NewRequest wraps NewRequestWithContext using context.Background.
NewRequestWithContext returns a new Request given a method, URL, and
optional body.
If the provided body is also an io.Closer, the returned
Request.Body is set to body and will be closed by the Client
methods Do, Post, and PostForm, and Transport.RoundTrip.
NewRequestWithContext returns a Request suitable for use with
Client.Do or Transport.RoundTrip. To create a request for use with
testing a Server Handler, either use the NewRequest function in the
net/http/httptest package, use ReadRequest, or manually update the
Request fields. For an outgoing client request, the context
controls the entire lifetime of a request and its response:
obtaining a connection, sending the request, and reading the
response headers and body. See the Request type's documentation for
the difference between inbound and outbound request fields.
If body is of type *bytes.Buffer, *bytes.Reader, or
*strings.Reader, the returned request's ContentLength is set to its
exact value (instead of -1), GetBody is populated (so 307 and 308
redirects can replay the body), and Body is set to NoBody if the
ContentLength is 0.
NewResponseController creates a ResponseController 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 ResponseController
will call them as appropriate:
Flush()
FlushError() error // alternative Flush returning an error
Hijack() (net.Conn, *bufio.ReadWriter, error)
SetReadDeadline(deadline time.Time) error
SetWriteDeadline(deadline time.Time) error
EnableFullDuplex() error
If the ResponseWriter does not support a method, ResponseController returns
an error matching ErrNotSupported.
NewServeMux allocates and returns a new ServeMux.
NotFound replies to the request with an HTTP 404 not found error.
NotFoundHandler returns a simple request handler
that replies to each request with a “404 page not found” reply.
ParseHTTPVersion parses an HTTP version string according to RFC 7230, section 2.6.
"HTTP/1.0" returns (1, 0, true). Note that strings without
a minor version, such as "HTTP/2", are not valid.
ParseTime parses a time header (such as the Date: header),
trying each of the three formats allowed by HTTP/1.1:
TimeFormat, time.RFC850, and time.ANSIC.
Post issues a POST to the specified URL.
Caller should close resp.Body when done reading from it.
If the provided body is an io.Closer, it is closed after the
request.
Post is a wrapper around DefaultClient.Post.
To set custom headers, use NewRequest and DefaultClient.Do.
See the Client.Do method documentation for details on how redirects
are handled.
To make a request with a specified context.Context, use NewRequestWithContext
and DefaultClient.Do.
PostForm issues a POST to the specified URL, with data's keys and
values URL-encoded as the request body.
The Content-Type header is set to application/x-www-form-urlencoded.
To set other headers, use NewRequest and DefaultClient.Do.
When err is nil, resp always contains a non-nil resp.Body.
Caller should close resp.Body when done reading from it.
PostForm is a wrapper around DefaultClient.PostForm.
See the Client.Do method documentation for details on how redirects
are handled.
To make a request with a specified context.Context, use NewRequestWithContext
and DefaultClient.Do.
ProxyFromEnvironment returns the URL of the proxy to use for a
given request, as indicated by the environment variables
HTTP_PROXY, HTTPS_PROXY and NO_PROXY (or the lowercase versions
thereof). Requests use the proxy from the environment variable
matching 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.
The schemes "http", "https", and "socks5" are supported.
An error is returned if the value is a different form.
A nil URL and nil error are returned if no proxy is defined in the
environment, or a proxy should not be used for the given request,
as defined by NO_PROXY.
As a special case, if req.URL.Host is "localhost" (with or without
a port number), then a nil URL and nil error will be returned.
ProxyURL returns a proxy function (for use in a Transport)
that always returns the same URL.
ReadRequest reads and parses an incoming request from b.
ReadRequest is a low-level function and should only be used for
specialized applications; most code should use the Server to read
requests and handle them via the Handler interface. ReadRequest
only supports HTTP/1.x requests. For HTTP/2, use golang.org/x/net/http2.
ReadResponse reads and returns an HTTP response from r.
The req parameter optionally specifies the Request that corresponds
to this Response. If nil, a GET request is assumed.
Clients must call resp.Body.Close when finished reading resp.Body.
After that call, clients can inspect resp.Trailer to find key/value
pairs included in the response trailer.
Redirect replies to the request with a redirect to url,
which may be a path relative to the request path.
The provided code should be in the 3xx range and is usually
StatusMovedPermanently, StatusFound or StatusSeeOther.
If the Content-Type header has not been set, Redirect sets it
to "text/html; charset=utf-8" and writes a small HTML body.
Setting the Content-Type header to any value, including nil,
disables that behavior.
RedirectHandler returns a request handler that redirects
each request it receives to the given url using the given
status code.
The provided code should be in the 3xx range and is usually
StatusMovedPermanently, StatusFound or StatusSeeOther.
Serve accepts incoming HTTP connections on the listener l,
creating a new service goroutine for each. The service goroutines
read requests and then call handler to reply to them.
The handler is typically nil, in which case the DefaultServeMux is used.
HTTP/2 support is only enabled if the Listener returns *tls.Conn
connections and they were configured with "h2" in the TLS
Config.NextProtos.
Serve always returns a non-nil error.
ServeContent replies to the request using the content in the
provided ReadSeeker. The main benefit of ServeContent over io.Copy
is that it handles Range requests properly, sets the MIME type, and
handles If-Match, If-Unmodified-Since, If-None-Match, If-Modified-Since,
and If-Range requests.
If the response's Content-Type header is not set, ServeContent
first tries to deduce the type from name's file extension and,
if that fails, falls back to reading the first block of the content
and passing it to DetectContentType.
The name is otherwise unused; in particular it can be empty and is
never sent in the response.
If modtime is not the zero time or Unix epoch, ServeContent
includes it in a Last-Modified header in the response. If the
request includes an If-Modified-Since header, ServeContent uses
modtime to decide whether the content needs to be sent at all.
The content's Seek method must work: ServeContent uses
a seek to the end of the content to determine its size.
If the caller has set w's ETag header formatted per RFC 7232, section 2.3,
ServeContent uses it to handle requests using If-Match, If-None-Match, or If-Range.
Note that *os.File implements the io.ReadSeeker interface.
ServeFile replies to the request with the contents of the named
file or directory.
If the provided file or directory name is a relative path, it is
interpreted relative to the current directory and may ascend to
parent directories. If the provided name is constructed from user
input, it should be sanitized before calling ServeFile.
As a precaution, ServeFile will reject requests where r.URL.Path
contains a ".." path element; this protects against callers who
might unsafely use filepath.Join on r.URL.Path without sanitizing
it and then use that filepath.Join result as the name argument.
As another special case, ServeFile redirects any request where r.URL.Path
ends in "/index.html" to the same path, without the final
"index.html". To avoid such redirects either modify the path or
use ServeContent.
Outside of those two special cases, ServeFile does not use
r.URL.Path for selecting the file or directory to serve; only the
file or directory provided in the name argument is used.
ServeTLS accepts incoming HTTPS connections on the listener l,
creating a new service goroutine for each. The service goroutines
read requests and then call handler to reply to them.
The handler is typically nil, in which case the DefaultServeMux is used.
Additionally, files containing a certificate and matching private key
for the server must be provided. If the certificate is signed by a
certificate authority, the certFile should be the concatenation
of the server's certificate, any intermediates, and the CA's certificate.
ServeTLS always returns a non-nil error.
SetCookie adds a Set-Cookie header to the provided ResponseWriter's headers.
The provided cookie must have a valid Name. Invalid cookies may be
silently dropped.
StatusText returns a text for the HTTP status code. It returns the empty
string if the code is unknown.
StripPrefix returns a handler that serves HTTP requests by removing the
given prefix from the request URL's Path (and RawPath if set) and invoking
the handler h. StripPrefix handles a request for a path that doesn't begin
with prefix by replying with an HTTP 404 not found error. The prefix must
match exactly: if the prefix in the request contains escaped characters
the reply is also an HTTP 404 not found error.
TimeoutHandler returns a Handler that runs h with the given time limit.
The new Handler calls h.ServeHTTP to handle each request, but if a
call runs for longer than its time limit, the handler responds with
a 503 Service Unavailable error and the given message in its body.
(If msg is empty, a suitable default message will be sent.)
After such a timeout, writes by h to its ResponseWriter will return
ErrHandlerTimeout.
TimeoutHandler supports the Pusher interface but does not support
the Hijacker or Flusher interfaces.
appendTime is a non-allocating version of []byte(t.UTC().Format(TimeFormat))
badRequestError is a literal string (used by in the server in HTML,
unescaped) to tell the user why their request was bad. It should
be plain text without user info or other embedded errors.
See 2 (end of page 4) https://www.ietf.org/rfc/rfc2617.txt
"To receive authorization, the client sends the userid and password,
separated by a single colon (":") character, within a base64
encoded string in the credentials."
It is not meant to be urlencoded.
bodyAllowedForStatus reports whether a given response status code
permits a body. See RFC 7230, section 3.3.
checkPreconditions evaluates request preconditions and reports whether a precondition
resulted in sending StatusNotModified or StatusPreconditionFailed.
cloneOrMakeHeader invokes Header.Clone but if the
result is nil, it'll instead make and return a non-nil Header.
cloneTLSConfig returns a shallow clone of cfg, or a new zero tls.Config if
cfg is nil. This is safe to call even if cfg is in active use by a TLS
client or server.
envProxyFunc returns a function that reads the
environment variable to determine the proxy address.
errNotSupported returns an error that Is ErrNotSupported,
but is not == to it.
etagStrongMatch reports whether a and b match using strong ETag comparison.
Assumes a and b are valid ETags.
etagWeakMatch reports whether a and b match using weak ETag comparison.
Assumes a and b are valid ETags.
Determine the expected body length, using RFC 7230 Section 3.3. This
function is not a method, because ultimately it should be shared by
ReadResponse and ReadRequest.
RFC 7234, section 5.4: Should treat
Pragma: no-cache
like
Cache-Control: no-cache
Parse the trailer header.
foreachHeaderElement splits v according to the "#rule" construction
in RFC 7230 section 7 and calls fn for each non-empty element.
Given a string of the form "host", "host:port", or "[ipv6::address]:port",
return true if the string includes a port.
hasToken reports whether token appears with v, ASCII
case-insensitive, with space or comma boundaries.
token must be all lowercase.
v may contain mixed cased.
checkConnHeaders checks whether req has any invalid connection-level headers.
per RFC 7540 section 8.1.2.2: Connection-Specific Header Fields.
Certain headers are special-cased as okay but not transmitted later.
checkValidHTTP2RequestHeaders checks whether h is a valid HTTP/2 request,
per RFC 7540 Section 8.1.2.2.
The returned error is reported to users.
checkWriteHeaderCode is a copy of net/http's checkWriteHeaderCode.
ConfigureServer adds HTTP/2 support to a net/http Server.
The configuration conf may be nil.
ConfigureServer must be called before s begins serving.
ConfigureTransport configures a net/http HTTP/1 Transport to use HTTP/2.
It returns an error if t1 has already been HTTP/2-enabled.
Use ConfigureTransports instead to configure the HTTP/2 Transport.
ConfigureTransports configures a net/http HTTP/1 Transport to use HTTP/2.
It returns a new HTTP/2 Transport for further configuration.
It returns an error if t1 has already been HTTP/2-enabled.
h1ServerKeepAlivesDisabled reports whether hs has its keep-alives
disabled. See comments on h1ServerShutdownChan above for why
the code is written this way.
isASCIIPrint returns whether s is ASCII and printable according to
https://tools.ietf.org/html/rfc20#section-4.2.
isBadCipher reports whether the cipher is blacklisted by the HTTP/2 spec.
References:
https://tools.ietf.org/html/rfc7540#appendix-A
Reject cipher suites from Appendix A.
"This list includes those cipher suites that do not
offer an ephemeral key exchange and those that are
based on the TLS null, stream or block cipher type"
isClosedConnError reports whether err is an error from use of a closed
network connection.
isConnectionCloseRequest reports whether req should use its own
connection for a single request and then close the connection.
isNoCachedConnError reports whether err is of type noCachedConnError
or its equivalent renamed type in net/http2's h2_bundle.go. Both types
may coexist in the same running program.
NewPriorityWriteScheduler constructs a WriteScheduler that schedules
frames by following HTTP/2 priorities as described in RFC 7540 Section 5.3.
If cfg is nil, default options are used.
NewRandomWriteScheduler constructs a WriteScheduler that ignores HTTP/2
priorities. Control frames like SETTINGS and PING are written before DATA
frames, but if no control frames are queued and multiple streams have queued
HEADERS or DATA frames, Pop selects a ready stream arbitrarily.
newRoundRobinWriteScheduler constructs a new write scheduler.
The round robin scheduler priorizes control frames
like SETTINGS and PING over DATA frames.
When there are no control frames to send, it performs a round-robin
selection from the ready streams.
shouldRetryDial reports whether the current request should
retry dialing after the call finished unsuccessfully, for example
if the dial was canceled because of a context cancellation or
deadline expiry.
shouldRetryRequest is called by RoundTrip when a request fails to get
response headers. It is always called with a non-nil error.
It returns either a request to retry (either the same request, or a
modified clone), or an error if the request can't be replayed.
shouldSendReqContentLength reports whether the http2.Transport should send
a "content-length" request header. This logic is basically a copy of the net/http
transferWriter.shouldSendContentLength.
The contentLength is the corrected contentLength (so 0 means actually 0, not unknown).
-1 means unknown.
splitHeaderBlock splits headerBlock into fragments so that each fragment fits
in a single frame, then calls fn for each fragment. firstFrag/lastFrag are true
for the first/last fragment, respectively.
takeInflows attempts to take n bytes from two inflows,
typically connection-level and stream-level flows.
It reports whether both windows have available capacity.
terminalReadFrameError reports whether err is an unrecoverable
error from ReadFrame and no other frames should be read.
validPseudoPath reports whether v is a valid :path pseudo-header
value. It must be either:
- a non-empty string starting with '/'
- the string '*', for OPTIONS requests.
For now this is only used a quick check for deciding when to clean
up Opaque URLs before sending requests from the Transport.
See golang.org/issue/16847
We used to enforce that the path also didn't start with "//", but
Google's GFE accepts such paths and Chrome sends them, so ignore
that part of the spec. See golang.org/issue/19103.
validWireHeaderFieldName reports whether v is a valid header field
name (key). See httpguts.ValidHeaderName for the base rules.
Further, http2 says:
"Just as in HTTP/1.x, header field names are strings of ASCII
characters that are compared in a case-insensitive
fashion. However, header field names MUST be converted to
lowercase prior to their encoding in HTTP/2. "
writeEndsStream reports whether w writes a frame that will transition
the stream to a half-closed local state. This returns false for RST_STREAM,
which closes the entire stream (not just the local half).
is408Message reports whether buf has the prefix of an
HTTP 408 Request Timeout response.
See golang.org/issue/32310.
isCommonNetReadError reports whether err is a common error
encountered during reading a request off the network when the
client has gone away or had its read fail somehow. This is used to
determine which logs are interesting enough to log about.
isCookieDomainName reports whether s is a valid domain name or a valid
domain name with a leading dot '.'. It is almost a direct copy of
package net's isDomainName.
isDomainOrSubdomain reports whether sub is a subdomain (or exact
match) of the parent domain.
Both domains must already be in canonical form.
Checks whether the encoding is explicitly "identity".
isKnownInMemoryReader reports whether r is a type known to not
block on Read. Its caller uses this as an optional optimization to
send fewer TCP packets.
isTT reports whether the provided byte is a tag-terminating byte (0xTT)
as defined in https://mimesniff.spec.whatwg.org/#terminology.
isUnsupportedTEError checks if the error is of type
unsupportedTEError. It is usually invoked with a non-nil err.
isWS reports whether the provided byte is a whitespace byte (0xWS)
as defined in https://mimesniff.spec.whatwg.org/#terminology.
isZeroTime reports whether t is obviously unspecified (either zero or Unix()=0).
knownRoundTripperImpl reports whether rt is a RoundTripper that's
maintained by the Go team and known to implement the latest
optional semantics (notably contexts). The Request is used
to check whether this particular request is using an alternate protocol,
in which case we need to check the RoundTripper for that protocol.
localRedirect gives a Moved Permanently response.
It does not convert relative paths to absolute paths like Redirect does.
logf prints to the ErrorLog of the *Server associated with request r
via ServerContextKey. If there's no associated server, or if ErrorLog
is nil, logging is done via the log package's standard logger.
mapOpenError maps the provided non-nil error from opening name
to a possibly better non-nil error. In particular, it turns OS-specific errors
about opening files in non-directories into fs.ErrNotExist. See Issues 18984 and 49552.
rangesMIMESize returns the number of bytes it takes to encode the
provided ranges as a multipart response.
readCookies parses all "Cookie" values from the header h and
returns the successfully parsed Cookies.
if filter isn't empty, only cookies of that name are returned.
readSetCookies parses all "Set-Cookie" values from
the header h and returns the successfully parsed Cookies.
msg is *Request or *Response.
redirectBehavior describes what should happen when the
client encounters a 3xx status code from the server.
refererForURL returns a referer without any authentication info or
an empty string if lastReq scheme is https and newReq scheme is http.
If the referer was explicitly set, then it will continue to be used.
relevantCaller searches the call stack for the first function outside of net/http.
The purpose of this function is to provide more helpful error messages.
removeEmptyPort strips the empty port in ":port" to ""
as mandated by RFC 3986 Section 6.2.3.
removeZone removes IPv6 zone identifier from host.
E.g., "[fe80::1%en0]:8080" to "[fe80::1]:8080"
requestBodyRemains reports whether future calls to Read
on rc might yield more data.
requestMethodUsuallyLacksBody reports whether the given request
method is one that typically does not involve a request body.
This is used by the Transport (via
transferWriter.shouldSendChunkedRequestBody) to determine whether
we try to test-read a byte from a non-nil Request.Body when
Request.outgoingLength() returns -1. See the comments in
shouldSendChunkedRequestBody.
resetProxyConfig is used by tests.
rewindBody returns a new request with the body rewound.
It returns req unmodified if the body does not need rewinding.
rewindBody takes care of closing req.Body when appropriate
(in all cases except when rewindBody returns req unmodified).
sanitizeCookieValue produces a suitable cookie-value from v.
https://tools.ietf.org/html/rfc6265#section-4.1.1
cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
; US-ASCII characters excluding CTLs,
; whitespace DQUOTE, comma, semicolon,
; and backslash
We loosen this as spaces and commas are common in cookie values
but we produce a quoted cookie-value if and only if v contains
commas or spaces.
See https://golang.org/issue/7243 for the discussion.
scanETag determines if a syntactically valid ETag is present at s. If so,
the ETag and remaining text after consuming ETag is returned. Otherwise,
it returns "", "".
send issues an HTTP request.
Caller should close resp.Body when done reading from it.
if name is empty, filename is unknown. (used for mime type, before sniffing)
if modtime.IsZero(), modtime is unknown.
content must be seeked to the beginning of the file.
The sizeFunc is called at most once. Its error, if any, is sent in the HTTP response.
setRequestCancel sets req.Cancel and adds a deadline context to req
if deadline is non-zero. The RoundTripper's type is used to
determine whether the legacy CancelRequest behavior should be used.
As background, there are three ways to cancel a request:
First was Transport.CancelRequest. (deprecated)
Second was Request.Cancel.
Third was Request.Context.
This function populates the second and third, and uses the first if it really needs to.
setupRewindBody returns a new request with a custom body wrapper
that can report whether the body needs rewinding.
This lets rewindBody avoid an error result when the request
does not have GetBody but the body hasn't been read at all yet.
Determine whether to hang up after sending a request and body, or
receiving a response and body
'header' is the request headers.
timeBeforeContextDeadline reports whether the non-zero Time t is
before ctx's deadline, if any. If ctx does not have a deadline, it
always reports true (the deadline is considered infinite).
tlsRecordHeaderLooksLikeHTTP reports whether a TLS record header
looks like it might've been a misdirected plaintext HTTP request.
toHTTPError returns a non-specific HTTP error message and status code
for a given non-nil error value. It's important that toHTTPError does not
actually return err.Error(), since msg and httpStatus are returned to users,
and historically Go's ServeContent always returned just "404 Not Found" for
all errors. We don't want to start leaking information in error messages.
unwrapNopCloser return the underlying reader and true if r is a NopCloser
else it return false.
urlErrorOp returns the (*url.Error).Op value to use for the
provided (*Request).Method value.
validCookieDomain reports whether v is a valid cookie domain-value.
validCookieExpires reports whether v is a valid cookie expires-value.
validNextProto reports whether the proto is a valid ALPN protocol name.
Everything is valid except the empty string and built-in protocol types,
so that those can't be overridden with alternate implementations.
writeStatusLine writes an HTTP/1.x Status-Line (RFC 7230 Section 3.1.2)
to bw. is11 is whether the HTTP request is HTTP/1.1. false means HTTP/1.0.
code is the response status code.
scratch is an optional scratch buffer. If it has at least capacity 3, it's used.
Package-Level Variables (total 176, in which 28 are exported)
DefaultClient is the default Client and is used by Get, Head, and Post.
DefaultServeMux is the default ServeMux used by Serve.
DefaultTransport is the default implementation of Transport and is
used by DefaultClient. It establishes network connections as needed
and caches them for reuse by subsequent calls. It uses HTTP proxies
as directed by the environment variables HTTP_PROXY, HTTPS_PROXY
and NO_PROXY (or the lowercase versions thereof).
ErrAbortHandler is a sentinel panic value to abort a handler.
While any panic from ServeHTTP aborts the response to the client,
panicking with ErrAbortHandler also suppresses logging of a stack
trace to the server's error log.
ErrBodyNotAllowed is returned by ResponseWriter.Write calls
when the HTTP method or response code does not permit a
body.
ErrBodyReadAfterClose is returned when reading a Request or Response
Body after the body has been closed. This typically happens when the body is
read after an HTTP Handler calls WriteHeader or Write on its
ResponseWriter.
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.
ErrHandlerTimeout is returned on ResponseWriter Write calls
in handlers which have timed out.
Deprecated: ErrHeaderTooLong is no longer returned by
anything in the net/http package. Callers should not
compare errors against this variable.
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.
ErrLineTooLong is returned when reading request or response bodies
with malformed chunked encoding.
ErrMissingBoundary is returned by Request.MultipartReader when the
request's Content-Type does not include a "boundary" parameter.
Deprecated: ErrMissingContentLength is no longer returned by
anything in the net/http package. Callers should not
compare errors against this variable.
ErrMissingFile is returned by FormFile when the provided file field name
is either not present in the request or not a file field.
ErrNoCookie is returned by Request's Cookie method when a cookie is not found.
ErrNoLocation is returned by Response's Location method
when no Location header is present.
ErrNotMultipart is returned by Request.MultipartReader when the
request's Content-Type is not multipart/form-data.
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.
ErrSchemeMismatch is returned when a server returns an HTTP response to an HTTPS client.
ErrServerClosed is returned by the Server's Serve, ServeTLS, ListenAndServe,
and ListenAndServeTLS methods after a call to Shutdown or Close.
Deprecated: ErrShortBody is no longer returned by
anything in the net/http package. Callers should not
compare errors against this variable.
ErrSkipAltProtocol is a sentinel error value defined by Transport.RegisterProtocol.
Deprecated: ErrUnexpectedTrailer is no longer returned by
anything in the net/http package. Callers should not
compare errors against this variable.
ErrUseLastResponse can be returned by Client.CheckRedirect hooks to
control how redirects are processed. If returned, the next request
is not sent and the most recent response is returned with its body
unclosed.
Deprecated: ErrWriteAfterFlush is no longer returned by
anything in the net/http package. Callers should not
compare errors against this variable.
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.
NoBody is an io.ReadCloser with no bytes. Read always returns EOF
and Close always returns nil. It can be used in an outgoing client
request to explicitly signal that a request has zero bytes.
An alternative, however, is to simply set Request.Body to nil.
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.
aLongTimeAgo is a non-zero time, far in the past, used for
immediate cancellation of network operations.
errCallerOwnsConn is an internal sentinel error used when we hand
off a writable response.Body to the caller. We use this to prevent
closing a net.Conn that is now owned by the caller.
errSeeker is returned by ServeContent's sizeFunc when the content
doesn't seek properly. The underlying Seeker's error text isn't
included in the sizeFunc reply so it's not sent over HTTP to end
users.
errServerClosedIdle is not seen by users for idempotent requests, but may be
seen by a user if the server shuts down an idle connection and sends its FIN
in flight with already-written POST body bytes from the client.
See https://github.com/golang/go/issues/19943#issuecomment-355607646
From http://httpwg.org/specs/rfc7540.html#rfc.section.8.1.2.2
Buffer chunks are allocated from a pool to reduce pressure on GC.
The maximum wasted space per dataBuffer is 2x the largest size class,
which happens when the dataBuffer has multiple chunks and there is
one unread byte in both the first and last chunks. We use a few size
classes to minimize overheads for servers that typically receive very
small request bodies.
TODO: Benchmark to determine if the pools are necessary. The GC may have
improved enough that we can instead allocate chunks like this:
make([]byte, max(16<<10, expectedBytesRemaining))
Buffer chunks are allocated from a pool to reduce pressure on GC.
The maximum wasted space per dataBuffer is 2x the largest size class,
which happens when the dataBuffer has multiple chunks and there is
one unread byte in both the first and last chunks. We use a few size
classes to minimize overheads for servers that typically receive very
small request bodies.
TODO: Benchmark to determine if the pools are necessary. The GC may have
improved enough that we can instead allocate chunks like this:
make([]byte, max(16<<10, expectedBytesRemaining))
ErrFrameTooLarge is returned from Framer.ReadFrame when the peer
sends a frame that is larger than declared with SetMaxReadFrameSize.
errFromPeer is a sentinel error value for StreamError.Cause to
indicate that the StreamError was sent from the peer over the wire
and wasn't locally generated in the Transport.
errHandlerPanicked is the error given to any callers blocked in a read from
Request.Body when the main goroutine panics. Since most handlers read in the
main ServeHTTP goroutine, this will show up rarely.
After sending GOAWAY with an error code (non-graceful shutdown), the
connection will close after goAwayTimeout.
If we close the connection immediately after sending GOAWAY, there may
be unsent data in our kernel receive buffer, which will cause the kernel
to send a TCP RST on close() instead of a FIN. This RST will abort the
connection immediately, whether or not the client had received the GOAWAY.
Ideally we should delay for at least 1 RTT + epsilon so the client has
a chance to read the GOAWAY and stop sending messages. Measuring RTT
is hard, so we approximate with 1 second. See golang.org/issue/18701.
This is a var so it can be shorter in tests, where all requests uses the
loopback interface making the expected RTT very small.
TODO: configurable?
maxWriteWaitBeforeConnReuse is how long the a Transport RoundTrip
will wait to see the Request's Body.Write result after getting a
response from the server. See comments in (*persistConn).wroteRequest.
In tests, we set this to a large value to avoid flakiness from inconsistent
recycling of connections.
multipartByReader is a sentinel value.
Its presence in Request.MultipartForm indicates that parsing of the request
body has been handed off to a MultipartReader instead of ParseMultipartForm.
omitBundledHTTP2 is set by omithttp2.go when the nethttpomithttp2
build tag is set. That means h2_bundle.go isn't compiled in and we
shouldn't try to use it.
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.
StateClosed represents a closed connection.
This is a terminal state. Hijacked connections do not
transition to StateClosed.
StateHijacked represents a hijacked connection.
This is a terminal state. It does not transition to StateClosed.
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.
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.
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
HTTP status codes as registered with IANA.
See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
TimeFormat is the time format to use when generating times in HTTP
headers. It is like time.RFC1123 but hard-codes GMT as the time
zone. The time being formatted must be in UTC for Format to
generate the correct format.
For parsing this time format, see ParseTime.
TrailerPrefix is a magic prefix for ResponseWriter.Header map keys
that, if present, signals that the map entry is actually for
the response trailers, and not the response headers. The prefix
is stripped after the ServeHTTP call finishes and the values are
sent in the trailers.
This mechanism is intended only for trailers that are not known
prior to the headers being written. If the set of trailers is fixed
or known before the header is written, the normal Go trailers mechanism
is preferred:
https://pkg.go.dev/net/http#ResponseWriter
https://pkg.go.dev/net/http#example-ResponseWriter-Trailers
This should be >= 512 bytes for DetectContentType,
but otherwise it's somewhat arbitrary.
NOTE: This is not intended to reflect the actual Go version being used.
It was changed at the time of Go 1.1 release because the former User-Agent
had ended up blocked by some intrusion detection systems.
See https://codereview.appspot.com/7532043.
bufWriterPoolBufferSize is the size of bufio.Writer's
buffers created using bufWriterPool.
TODO: pick a less arbitrary value? this is a bit under
(3 x typical 1500 byte MTU) at least. Other than that,
not much thought went into it.
initialMaxConcurrentStreams is a connections maxConcurrentStreams until
it's received servers initial SETTINGS frame, which corresponds with the
spec's minimum recommended value.
maxCachedCanonicalHeadersKeysSize is an arbitrarily-chosen limit on the size
of the entries in the canonHeader cache.
This should be larger than the size of unique, uncommon header keys likely to
be sent by the peer, while not so high as to permit unreasonable memory usage
if the peer sends an unbounded number of unique header keys.
HTTP/2 stream states.
See http://tools.ietf.org/html/rfc7540#section-5.1.
For simplicity, the server code merges "reserved (local)" into
"half-closed (remote)". This is one less state transition to track.
The only downside is that we send PUSH_PROMISEs slightly less
liberally than allowable. More discussion here:
https://lists.w3.org/Archives/Public/ietf-http-wg/2016JulSep/0599.html
"reserved (remote)" is omitted since the client code does not
support server push.
HTTP/2 stream states.
See http://tools.ietf.org/html/rfc7540#section-5.1.
For simplicity, the server code merges "reserved (local)" into
"half-closed (remote)". This is one less state transition to track.
The only downside is that we send PUSH_PROMISEs slightly less
liberally than allowable. More discussion here:
https://lists.w3.org/Archives/Public/ietf-http-wg/2016JulSep/0599.html
"reserved (remote)" is omitted since the client code does not
support server push.
HTTP/2 stream states.
See http://tools.ietf.org/html/rfc7540#section-5.1.
For simplicity, the server code merges "reserved (local)" into
"half-closed (remote)". This is one less state transition to track.
The only downside is that we send PUSH_PROMISEs slightly less
liberally than allowable. More discussion here:
https://lists.w3.org/Archives/Public/ietf-http-wg/2016JulSep/0599.html
"reserved (remote)" is omitted since the client code does not
support server push.
HTTP/2 stream states.
See http://tools.ietf.org/html/rfc7540#section-5.1.
For simplicity, the server code merges "reserved (local)" into
"half-closed (remote)". This is one less state transition to track.
The only downside is that we send PUSH_PROMISEs slightly less
liberally than allowable. More discussion here:
https://lists.w3.org/Archives/Public/ietf-http-wg/2016JulSep/0599.html
"reserved (remote)" is omitted since the client code does not
support server push.
HTTP/2 stream states.
See http://tools.ietf.org/html/rfc7540#section-5.1.
For simplicity, the server code merges "reserved (local)" into
"half-closed (remote)". This is one less state transition to track.
The only downside is that we send PUSH_PROMISEs slightly less
liberally than allowable. More discussion here:
https://lists.w3.org/Archives/Public/ietf-http-wg/2016JulSep/0599.html
"reserved (remote)" is omitted since the client code does not
support server push.
TrailerPrefix is a magic prefix for ResponseWriter.Header map keys
that, if present, signals that the map entry is actually for
the response trailers, and not the response headers. The prefix
is stripped after the ServeHTTP call finishes and the values are
sent in the trailers.
This mechanism is intended only for trailers that are not known
prior to the headers being written. If the set of trailers is fixed
or known before the header is written, the normal Go trailers mechanism
is preferred:
https://golang.org/pkg/net/http/#ResponseWriter
https://golang.org/pkg/net/http/#example_ResponseWriter_trailers
transportDefaultConnFlow is how many connection-level flow control
tokens we give the server at start-up, past the default 64k.
transportDefaultStreamFlow is how many stream-level flow
control tokens we announce to the peer, and how many bytes
we buffer per stream.
maxInt64 is the effective "infinite" value for the Server and
Transport's byte-limiting readers.
maxPostHandlerReadBytes is the max number of Request.Body bytes not
consumed by a handler that the server will read from the client
in order to keep a connection alive. If there are more bytes than
this then the server to be paranoid instead sends a "Connection:
close" response.
This number is approximately what a typical machine's TCP buffer
size is anyway. (if we have the bytes on the machine, we might as
well read them)
rstAvoidanceDelay is the amount of time we sleep after closing the
write side of a TCP connection before closing the entire socket.
By sleeping, we increase the chances that the client sees our FIN
and processes its final data before they process the subsequent RST
from closing a connection with known unread data.
This RST seems to occur mostly on BSD systems. (And Windows?)
This timeout is somewhat arbitrary (~latency around the planet).
shutdownPollIntervalMax is the max polling interval when checking
quiescence during Server.Shutdown. Polling starts with a small
interval and backs off to the max.
Ideally we could find a solution that doesn't involve polling,
but which also doesn't have a high runtime cost (and doesn't
involve any contentious mutexes), but that is left as an
exercise for the reader.
The pages are generated with Goldsv0.6.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds.