Skip to content

Instantly share code, notes, and snippets.

@slimsag
Created May 6, 2021 23:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slimsag/069d8498890ea6a3ec85dee3ef6f18c8 to your computer and use it in GitHub Desktop.
Save slimsag/069d8498890ea6a3ec85dee3ef6f18c8 to your computer and use it in GitHub Desktop.

Index

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/](http://example.com/)")
...
resp, err := http.Post("[http://example.com/upload](http://example.com/upload)", "image/jpeg", &buf)
...
resp, err := http.PostForm("[http://example.com/form](http://example.com/form)",
	url.Values{"key": {"Value"}, "id": {"123"}})

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

resp, err := http.Get("[http://example.com/](http://example.com/)")
if err != nil {
	// handle error
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
// ...

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

client := &http.Client{
	CheckRedirect: redirectPolicyFunc,
}

resp, err := client.Get("[http://example.com](http://example.com)")
// ...

req, err := http.NewRequest("GET", "[http://example.com](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](https://example.com)")

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

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

http.Handle("/foo", fooHandler)

http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
})

log.Fatal(http.ListenAndServe(":8080", nil))

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

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

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

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

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

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

Index

const maxBodySlurpSize = 2 << 10

Close the previous response's body. But read at least some of the body so if it's small the underlying TCP connection will be re-used. No need to check for errors: if it fails, the Transport won't reuse it anyway.

const SameSiteDefaultMode SameSite = iota + 1
const SameSiteLaxMode
const SameSiteStrictMode
const SameSiteNoneMode
const extraCookieLength = 110

extraCookieLength derived from typical length of cookie attributes see RFC 6265 Sec 4.1.

const condNone condResult = iota
const condTrue
const condFalse
const indexPage = "/index.html"
const b = "bytes="
const http2cipher_TLS_NULL_WITH_NULL_NULL uint16 = 0x0000
const http2cipher_TLS_RSA_WITH_NULL_MD5 uint16 = 0x0001
const http2cipher_TLS_RSA_WITH_NULL_SHA uint16 = 0x0002
const http2cipher_TLS_RSA_EXPORT_WITH_RC4_40_MD5 uint16 = 0x0003
const http2cipher_TLS_RSA_WITH_RC4_128_MD5 uint16 = 0x0004
const http2cipher_TLS_RSA_WITH_RC4_128_SHA uint16 = 0x0005
const http2cipher_TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 uint16 = 0x0006
const http2cipher_TLS_RSA_WITH_IDEA_CBC_SHA uint16 = 0x0007
const http2cipher_TLS_RSA_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x0008
const http2cipher_TLS_RSA_WITH_DES_CBC_SHA uint16 = 0x0009
const http2cipher_TLS_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0x000A
const http2cipher_TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x000B
const http2cipher_TLS_DH_DSS_WITH_DES_CBC_SHA uint16 = 0x000C
const http2cipher_TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA uint16 = 0x000D
const http2cipher_TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x000E
const http2cipher_TLS_DH_RSA_WITH_DES_CBC_SHA uint16 = 0x000F
const http2cipher_TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0x0010
const http2cipher_TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x0011
const http2cipher_TLS_DHE_DSS_WITH_DES_CBC_SHA uint16 = 0x0012
const http2cipher_TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA uint16 = 0x0013
const http2cipher_TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x0014
const http2cipher_TLS_DHE_RSA_WITH_DES_CBC_SHA uint16 = 0x0015
const http2cipher_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0x0016
const http2cipher_TLS_DH_anon_EXPORT_WITH_RC4_40_MD5 uint16 = 0x0017
const http2cipher_TLS_DH_anon_WITH_RC4_128_MD5 uint16 = 0x0018
const http2cipher_TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x0019
const http2cipher_TLS_DH_anon_WITH_DES_CBC_SHA uint16 = 0x001A
const http2cipher_TLS_DH_anon_WITH_3DES_EDE_CBC_SHA uint16 = 0x001B
const http2cipher_TLS_KRB5_WITH_DES_CBC_SHA uint16 = 0x001E

Reserved uint16 = 0x001C-1D

const http2cipher_TLS_KRB5_WITH_3DES_EDE_CBC_SHA uint16 = 0x001F
const http2cipher_TLS_KRB5_WITH_RC4_128_SHA uint16 = 0x0020
const http2cipher_TLS_KRB5_WITH_IDEA_CBC_SHA uint16 = 0x0021
const http2cipher_TLS_KRB5_WITH_DES_CBC_MD5 uint16 = 0x0022
const http2cipher_TLS_KRB5_WITH_3DES_EDE_CBC_MD5 uint16 = 0x0023
const http2cipher_TLS_KRB5_WITH_RC4_128_MD5 uint16 = 0x0024
const http2cipher_TLS_KRB5_WITH_IDEA_CBC_MD5 uint16 = 0x0025
const http2cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA uint16 = 0x0026
const http2cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA uint16 = 0x0027
const http2cipher_TLS_KRB5_EXPORT_WITH_RC4_40_SHA uint16 = 0x0028
const http2cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5 uint16 = 0x0029
const http2cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5 uint16 = 0x002A
const http2cipher_TLS_KRB5_EXPORT_WITH_RC4_40_MD5 uint16 = 0x002B
const http2cipher_TLS_PSK_WITH_NULL_SHA uint16 = 0x002C
const http2cipher_TLS_DHE_PSK_WITH_NULL_SHA uint16 = 0x002D
const http2cipher_TLS_RSA_PSK_WITH_NULL_SHA uint16 = 0x002E
const http2cipher_TLS_RSA_WITH_AES_128_CBC_SHA uint16 = 0x002F
const http2cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA uint16 = 0x0030
const http2cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA uint16 = 0x0031
const http2cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA uint16 = 0x0032
const http2cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA uint16 = 0x0033
const http2cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA uint16 = 0x0034
const http2cipher_TLS_RSA_WITH_AES_256_CBC_SHA uint16 = 0x0035
const http2cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA uint16 = 0x0036
const http2cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA uint16 = 0x0037
const http2cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA uint16 = 0x0038
const http2cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA uint16 = 0x0039
const http2cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA uint16 = 0x003A
const http2cipher_TLS_RSA_WITH_NULL_SHA256 uint16 = 0x003B
const http2cipher_TLS_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0x003C
const http2cipher_TLS_RSA_WITH_AES_256_CBC_SHA256 uint16 = 0x003D
const http2cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA256 uint16 = 0x003E
const http2cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0x003F
const http2cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 uint16 = 0x0040
const http2cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0041
const http2cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0042
const http2cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0043
const http2cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0044
const http2cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0045
const http2cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0046
const http2cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0x0067

Reserved uint16 = 0x0047-4F Reserved uint16 = 0x0050-58 Reserved uint16 = 0x0059-5C Unassigned uint16 = 0x005D-5F Reserved uint16 = 0x0060-66

const http2cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA256 uint16 = 0x0068
const http2cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA256 uint16 = 0x0069
const http2cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 uint16 = 0x006A
const http2cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 uint16 = 0x006B
const http2cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA256 uint16 = 0x006C
const http2cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA256 uint16 = 0x006D
const http2cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0084

Unassigned uint16 = 0x006E-83

const http2cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0085
const http2cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0086
const http2cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0087
const http2cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0088
const http2cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0089
const http2cipher_TLS_PSK_WITH_RC4_128_SHA uint16 = 0x008A
const http2cipher_TLS_PSK_WITH_3DES_EDE_CBC_SHA uint16 = 0x008B
const http2cipher_TLS_PSK_WITH_AES_128_CBC_SHA uint16 = 0x008C
const http2cipher_TLS_PSK_WITH_AES_256_CBC_SHA uint16 = 0x008D
const http2cipher_TLS_DHE_PSK_WITH_RC4_128_SHA uint16 = 0x008E
const http2cipher_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA uint16 = 0x008F
const http2cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA uint16 = 0x0090
const http2cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA uint16 = 0x0091
const http2cipher_TLS_RSA_PSK_WITH_RC4_128_SHA uint16 = 0x0092
const http2cipher_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA uint16 = 0x0093
const http2cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA uint16 = 0x0094
const http2cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA uint16 = 0x0095
const http2cipher_TLS_RSA_WITH_SEED_CBC_SHA uint16 = 0x0096
const http2cipher_TLS_DH_DSS_WITH_SEED_CBC_SHA uint16 = 0x0097
const http2cipher_TLS_DH_RSA_WITH_SEED_CBC_SHA uint16 = 0x0098
const http2cipher_TLS_DHE_DSS_WITH_SEED_CBC_SHA uint16 = 0x0099
const http2cipher_TLS_DHE_RSA_WITH_SEED_CBC_SHA uint16 = 0x009A
const http2cipher_TLS_DH_anon_WITH_SEED_CBC_SHA uint16 = 0x009B
const http2cipher_TLS_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0x009C
const http2cipher_TLS_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0x009D
const http2cipher_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0x009E
const http2cipher_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0x009F
const http2cipher_TLS_DH_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0x00A0
const http2cipher_TLS_DH_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0x00A1
const http2cipher_TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 uint16 = 0x00A2
const http2cipher_TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 uint16 = 0x00A3
const http2cipher_TLS_DH_DSS_WITH_AES_128_GCM_SHA256 uint16 = 0x00A4
const http2cipher_TLS_DH_DSS_WITH_AES_256_GCM_SHA384 uint16 = 0x00A5
const http2cipher_TLS_DH_anon_WITH_AES_128_GCM_SHA256 uint16 = 0x00A6
const http2cipher_TLS_DH_anon_WITH_AES_256_GCM_SHA384 uint16 = 0x00A7
const http2cipher_TLS_PSK_WITH_AES_128_GCM_SHA256 uint16 = 0x00A8
const http2cipher_TLS_PSK_WITH_AES_256_GCM_SHA384 uint16 = 0x00A9
const http2cipher_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 uint16 = 0x00AA
const http2cipher_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 uint16 = 0x00AB
const http2cipher_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256 uint16 = 0x00AC
const http2cipher_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384 uint16 = 0x00AD
const http2cipher_TLS_PSK_WITH_AES_128_CBC_SHA256 uint16 = 0x00AE
const http2cipher_TLS_PSK_WITH_AES_256_CBC_SHA384 uint16 = 0x00AF
const http2cipher_TLS_PSK_WITH_NULL_SHA256 uint16 = 0x00B0
const http2cipher_TLS_PSK_WITH_NULL_SHA384 uint16 = 0x00B1
const http2cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 uint16 = 0x00B2
const http2cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 uint16 = 0x00B3
const http2cipher_TLS_DHE_PSK_WITH_NULL_SHA256 uint16 = 0x00B4
const http2cipher_TLS_DHE_PSK_WITH_NULL_SHA384 uint16 = 0x00B5
const http2cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256 uint16 = 0x00B6
const http2cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384 uint16 = 0x00B7
const http2cipher_TLS_RSA_PSK_WITH_NULL_SHA256 uint16 = 0x00B8
const http2cipher_TLS_RSA_PSK_WITH_NULL_SHA384 uint16 = 0x00B9
const http2cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BA
const http2cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BB
const http2cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BC
const http2cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BD
const http2cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BE
const http2cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BF
const http2cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C0
const http2cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C1
const http2cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C2
const http2cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C3
const http2cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C4
const http2cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C5
const http2cipher_TLS_EMPTY_RENEGOTIATION_INFO_SCSV uint16 = 0x00FF

Unassigned uint16 = 0x00C6-FE

const http2cipher_TLS_FALLBACK_SCSV uint16 = 0x5600

Unassigned uint16 = 0x01-55,*

const http2cipher_TLS_ECDH_ECDSA_WITH_NULL_SHA uint16 = 0xC001

Unassigned uint16 = 0x5601 - 0xC000

const http2cipher_TLS_ECDH_ECDSA_WITH_RC4_128_SHA uint16 = 0xC002
const http2cipher_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC003
const http2cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA uint16 = 0xC004
const http2cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA uint16 = 0xC005
const http2cipher_TLS_ECDHE_ECDSA_WITH_NULL_SHA uint16 = 0xC006
const http2cipher_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA uint16 = 0xC007
const http2cipher_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC008
const http2cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA uint16 = 0xC009
const http2cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA uint16 = 0xC00A
const http2cipher_TLS_ECDH_RSA_WITH_NULL_SHA uint16 = 0xC00B
const http2cipher_TLS_ECDH_RSA_WITH_RC4_128_SHA uint16 = 0xC00C
const http2cipher_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC00D
const http2cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA uint16 = 0xC00E
const http2cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA uint16 = 0xC00F
const http2cipher_TLS_ECDHE_RSA_WITH_NULL_SHA uint16 = 0xC010
const http2cipher_TLS_ECDHE_RSA_WITH_RC4_128_SHA uint16 = 0xC011
const http2cipher_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC012
const http2cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA uint16 = 0xC013
const http2cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA uint16 = 0xC014
const http2cipher_TLS_ECDH_anon_WITH_NULL_SHA uint16 = 0xC015
const http2cipher_TLS_ECDH_anon_WITH_RC4_128_SHA uint16 = 0xC016
const http2cipher_TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA uint16 = 0xC017
const http2cipher_TLS_ECDH_anon_WITH_AES_128_CBC_SHA uint16 = 0xC018
const http2cipher_TLS_ECDH_anon_WITH_AES_256_CBC_SHA uint16 = 0xC019
const http2cipher_TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC01A
const http2cipher_TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC01B
const http2cipher_TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA uint16 = 0xC01C
const http2cipher_TLS_SRP_SHA_WITH_AES_128_CBC_SHA uint16 = 0xC01D
const http2cipher_TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA uint16 = 0xC01E
const http2cipher_TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA uint16 = 0xC01F
const http2cipher_TLS_SRP_SHA_WITH_AES_256_CBC_SHA uint16 = 0xC020
const http2cipher_TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA uint16 = 0xC021
const http2cipher_TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA uint16 = 0xC022
const http2cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 uint16 = 0xC023
const http2cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 uint16 = 0xC024
const http2cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 uint16 = 0xC025
const http2cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 uint16 = 0xC026
const http2cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0xC027
const http2cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 uint16 = 0xC028
const http2cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0xC029
const http2cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 uint16 = 0xC02A
const http2cipher_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 uint16 = 0xC02B
const http2cipher_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 uint16 = 0xC02C
const http2cipher_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 uint16 = 0xC02D
const http2cipher_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 uint16 = 0xC02E
const http2cipher_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0xC02F
const http2cipher_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0xC030
const http2cipher_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0xC031
const http2cipher_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0xC032
const http2cipher_TLS_ECDHE_PSK_WITH_RC4_128_SHA uint16 = 0xC033
const http2cipher_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA uint16 = 0xC034
const http2cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA uint16 = 0xC035
const http2cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA uint16 = 0xC036
const http2cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 uint16 = 0xC037
const http2cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 uint16 = 0xC038
const http2cipher_TLS_ECDHE_PSK_WITH_NULL_SHA uint16 = 0xC039
const http2cipher_TLS_ECDHE_PSK_WITH_NULL_SHA256 uint16 = 0xC03A
const http2cipher_TLS_ECDHE_PSK_WITH_NULL_SHA384 uint16 = 0xC03B
const http2cipher_TLS_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC03C
const http2cipher_TLS_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC03D
const http2cipher_TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC03E
const http2cipher_TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC03F
const http2cipher_TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC040
const http2cipher_TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC041
const http2cipher_TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC042
const http2cipher_TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC043
const http2cipher_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC044
const http2cipher_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC045
const http2cipher_TLS_DH_anon_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC046
const http2cipher_TLS_DH_anon_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC047
const http2cipher_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC048
const http2cipher_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC049
const http2cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC04A
const http2cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC04B
const http2cipher_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC04C
const http2cipher_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC04D
const http2cipher_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC04E
const http2cipher_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC04F
const http2cipher_TLS_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC050
const http2cipher_TLS_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC051
const http2cipher_TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC052
const http2cipher_TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC053
const http2cipher_TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC054
const http2cipher_TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC055
const http2cipher_TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC056
const http2cipher_TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC057
const http2cipher_TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC058
const http2cipher_TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC059
const http2cipher_TLS_DH_anon_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC05A
const http2cipher_TLS_DH_anon_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC05B
const http2cipher_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC05C
const http2cipher_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC05D
const http2cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC05E
const http2cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC05F
const http2cipher_TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC060
const http2cipher_TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC061
const http2cipher_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC062
const http2cipher_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC063
const http2cipher_TLS_PSK_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC064
const http2cipher_TLS_PSK_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC065
const http2cipher_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC066
const http2cipher_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC067
const http2cipher_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC068
const http2cipher_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC069
const http2cipher_TLS_PSK_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC06A
const http2cipher_TLS_PSK_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC06B
const http2cipher_TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC06C
const http2cipher_TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC06D
const http2cipher_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC06E
const http2cipher_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC06F
const http2cipher_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC070
const http2cipher_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC071
const http2cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC072
const http2cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC073
const http2cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC074
const http2cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC075
const http2cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC076
const http2cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC077
const http2cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC078
const http2cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC079
const http2cipher_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC07A
const http2cipher_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC07B
const http2cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC07C
const http2cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC07D
const http2cipher_TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC07E
const http2cipher_TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC07F
const http2cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC080
const http2cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC081
const http2cipher_TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC082
const http2cipher_TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC083
const http2cipher_TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC084
const http2cipher_TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC085
const http2cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC086
const http2cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC087
const http2cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC088
const http2cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC089
const http2cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC08A
const http2cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC08B
const http2cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC08C
const http2cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC08D
const http2cipher_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC08E
const http2cipher_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC08F
const http2cipher_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC090
const http2cipher_TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC091
const http2cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC092
const http2cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC093
const http2cipher_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC094
const http2cipher_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC095
const http2cipher_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC096
const http2cipher_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC097
const http2cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC098
const http2cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC099
const http2cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC09A
const http2cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC09B
const http2cipher_TLS_RSA_WITH_AES_128_CCM uint16 = 0xC09C
const http2cipher_TLS_RSA_WITH_AES_256_CCM uint16 = 0xC09D
const http2cipher_TLS_DHE_RSA_WITH_AES_128_CCM uint16 = 0xC09E
const http2cipher_TLS_DHE_RSA_WITH_AES_256_CCM uint16 = 0xC09F
const http2cipher_TLS_RSA_WITH_AES_128_CCM_8 uint16 = 0xC0A0
const http2cipher_TLS_RSA_WITH_AES_256_CCM_8 uint16 = 0xC0A1
const http2cipher_TLS_DHE_RSA_WITH_AES_128_CCM_8 uint16 = 0xC0A2
const http2cipher_TLS_DHE_RSA_WITH_AES_256_CCM_8 uint16 = 0xC0A3
const http2cipher_TLS_PSK_WITH_AES_128_CCM uint16 = 0xC0A4
const http2cipher_TLS_PSK_WITH_AES_256_CCM uint16 = 0xC0A5
const http2cipher_TLS_DHE_PSK_WITH_AES_128_CCM uint16 = 0xC0A6
const http2cipher_TLS_DHE_PSK_WITH_AES_256_CCM uint16 = 0xC0A7
const http2cipher_TLS_PSK_WITH_AES_128_CCM_8 uint16 = 0xC0A8
const http2cipher_TLS_PSK_WITH_AES_256_CCM_8 uint16 = 0xC0A9
const http2cipher_TLS_PSK_DHE_WITH_AES_128_CCM_8 uint16 = 0xC0AA
const http2cipher_TLS_PSK_DHE_WITH_AES_256_CCM_8 uint16 = 0xC0AB
const http2cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CCM uint16 = 0xC0AC
const http2cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CCM uint16 = 0xC0AD
const http2cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 uint16 = 0xC0AE
const http2cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 uint16 = 0xC0AF
const http2cipher_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCA8

Unassigned uint16 = 0xC0B0-FF Unassigned uint16 = 0xC1-CB,* Unassigned uint16 = 0xCC00-A7

const http2cipher_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCA9
const http2cipher_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAA
const http2cipher_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAB
const http2cipher_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAC
const http2cipher_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAD
const http2cipher_TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAE
const http2dialOnMiss = true
const http2noDialOnMiss = false
const singleUse = true
const singleUse = false // shared conn
const http2ErrCodeNo http2ErrCode = 0x0
const http2ErrCodeProtocol http2ErrCode = 0x1
const http2ErrCodeInternal http2ErrCode = 0x2
const http2ErrCodeFlowControl http2ErrCode = 0x3
const http2ErrCodeSettingsTimeout http2ErrCode = 0x4
const http2ErrCodeStreamClosed http2ErrCode = 0x5
const http2ErrCodeFrameSize http2ErrCode = 0x6
const http2ErrCodeRefusedStream http2ErrCode = 0x7
const http2ErrCodeCancel http2ErrCode = 0x8
const http2ErrCodeCompression http2ErrCode = 0x9
const http2ErrCodeConnect http2ErrCode = 0xa
const http2ErrCodeEnhanceYourCalm http2ErrCode = 0xb
const http2ErrCodeInadequateSecurity http2ErrCode = 0xc
const http2ErrCodeHTTP11Required http2ErrCode = 0xd
const http2frameHeaderLen = 9
const http2FrameData http2FrameType = 0x0
const http2FrameHeaders http2FrameType = 0x1
const http2FramePriority http2FrameType = 0x2
const http2FrameRSTStream http2FrameType = 0x3
const http2FrameSettings http2FrameType = 0x4
const http2FramePushPromise http2FrameType = 0x5
const http2FramePing http2FrameType = 0x6
const http2FrameGoAway http2FrameType = 0x7
const http2FrameWindowUpdate http2FrameType = 0x8
const http2FrameContinuation http2FrameType = 0x9
const http2FlagDataEndStream http2Flags = 0x1

Frame-specific FrameHeader flag bits.

Data Frame

const http2FlagDataPadded http2Flags = 0x8

Frame-specific FrameHeader flag bits.

const http2FlagHeadersEndStream http2Flags = 0x1

Frame-specific FrameHeader flag bits.

Headers Frame

const http2FlagHeadersEndHeaders http2Flags = 0x4

Frame-specific FrameHeader flag bits.

const http2FlagHeadersPadded http2Flags = 0x8

Frame-specific FrameHeader flag bits.

const http2FlagHeadersPriority http2Flags = 0x20

Frame-specific FrameHeader flag bits.

const http2FlagSettingsAck http2Flags = 0x1

Frame-specific FrameHeader flag bits.

Settings Frame

const http2FlagPingAck http2Flags = 0x1

Frame-specific FrameHeader flag bits.

Ping Frame

const http2FlagContinuationEndHeaders http2Flags = 0x4

Frame-specific FrameHeader flag bits.

Continuation Frame

const http2FlagPushPromiseEndHeaders http2Flags = 0x4

Frame-specific FrameHeader flag bits.

const http2FlagPushPromisePadded http2Flags = 0x8

Frame-specific FrameHeader flag bits.

const http2minMaxFrameSize = 1 << 14
const http2maxFrameSize = 1<<24 - 1
const max = 256
const http2ClientPreface = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"

ClientPreface is the string that must be sent by new connections from clients.

const http2initialMaxFrameSize = 16384

SETTINGS_MAX_FRAME_SIZE default http://http2.github.io/http2-spec/#rfc.section.6.5.2

const http2NextProtoTLS = "h2"

NextProtoTLS is the NPN/ALPN protocol negotiated during HTTP/2's TLS setup.

const http2initialHeaderTableSize = 4096

http://http2.github.io/http2-spec/#SettingValues

const http2initialWindowSize = 65535 // 6.9.2 Initial Flow Control Window Size
const http2defaultMaxReadFrameSize = 1 << 20
const http2stateIdle http2streamState = iota

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.

const http2stateOpen

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.

const http2stateHalfClosedLocal

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.

const http2stateHalfClosedRemote

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.

const http2stateClosed

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.

const http2SettingHeaderTableSize http2SettingID = 0x1
const http2SettingEnablePush http2SettingID = 0x2
const http2SettingMaxConcurrentStreams http2SettingID = 0x3
const http2SettingInitialWindowSize http2SettingID = 0x4
const http2SettingMaxFrameSize http2SettingID = 0x5
const http2SettingMaxHeaderListSize http2SettingID = 0x6
const http2bufWriterPoolBufferSize = 4 << 10

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.

const http2prefaceTimeout = 10 * time.Second
const http2firstSettingsTimeout = 2 * time.Second // should be in-flight with preface anyway
const http2handlerChunkWriteSize = 4 << 10
const http2defaultMaxStreams = 250 // TODO: make this 100 as the GFE seems to?
const http2maxQueuedControlFrames = 10000
const perFieldOverhead = 32 // per http2 spec

http2's count is in a slightly different unit and includes 32 bytes per pair. So, take the net/http.Server value and pad it up a bit, assuming 10 headers.

const typicalHeaders = 10 // conservative
const WSAECONNABORTED = 10053
const WSAECONNRESET = 10054
const size = 64 << 10
const statusRequestHeaderFieldsTooLarge = 431 // only in Go 1.6+

10.5.1 Limits on Header Block Size: .. "A server that receives a larger header block than it is willing to handle can send an HTTP 431 (Request Header Fields Too Large) status code"

const maxUint31 = 1<<31 - 1

"The legal range for the increment to the flow control window is 1 to 2^31-1 (2,147,483,647) octets." A Go Read call on 64-bit machines could in theory read a larger Read than this. Very unlikely, but we handle it here rather than elsewhere for now.

const http2TrailerPrefix = "Trailer:"

TrailerPrefix is a magic prefix for ResponseWriter.Header map keys that, if present, signals that the map entry is actually for the response trailers, and not the response headers. The prefix is stripped after the ServeHTTP call finishes and the values are sent in the trailers.

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

[https://golang.org/pkg/net/http/#ResponseWriter](https://golang.org/pkg/net/http/#ResponseWriter)
[https://golang.org/pkg/net/http/#example_ResponseWriter_trailers](https://golang.org/pkg/net/http/#example_ResponseWriter_trailers)

const http2transportDefaultConnFlow = 1 << 30

transportDefaultConnFlow is how many connection-level flow control tokens we give the server at start-up, past the default 64k.

const http2transportDefaultStreamFlow = 4 << 20

transportDefaultStreamFlow is how many stream-level flow control tokens we announce to the peer, and how many bytes we buffer per stream.

const http2transportDefaultStreamMinRefresh = 4 << 10

transportDefaultStreamMinRefresh is the minimum number of bytes we'll send a stream-level WINDOW_UPDATE for at a time.

const http2defaultUserAgent = "Go-http-client/2.0"
const http2maxAllocFrameSize = 512 << 10
const maxBufs = 4 // arbitrary; 4 concurrent requests per conn? investigate.
const max1xxResponses = 5 // arbitrary bound on number of informational responses, same as net/http
const hugeDuration = 365 * 24 * time.Hour

Arm the timer with a very large duration, which we'll intentionally lower later. It has to be large now because we need a handle to it before writing the headers, but the s.delay value is defined to not start until after the request headers were written.

const settingSize = 6 // uint16 + uint32
const maxFrameSize = 16384

For now we're lazy and just pick the minimum MAX_FRAME_SIZE that all peers must support (16KB). Later we could care more and send larger frames if the peer advertised it, but there's little point. Most headers are small anyway (so we generally won't have CONTINUATION frames), and extra frames only waste 9 bytes anyway.

const http2priorityDefaultWeight = 15 // 16 = 15 + 1

RFC 7540, Section 5.3.5: the default weight is 16.

const http2priorityNodeOpen http2priorityNodeState = iota
const http2priorityNodeClosed
const http2priorityNodeIdle
const maxInt64 = 1<<63 - 1

maxInt64 is the effective "infinite" value for the Server and Transport's byte-limiting readers.

const MethodGet = "GET"

Common HTTP methods.

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

const MethodHead = "HEAD"

Common HTTP methods.

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

const MethodPost = "POST"

Common HTTP methods.

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

const MethodPut = "PUT"

Common HTTP methods.

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

const MethodPatch = "PATCH" // RFC 5789

Common HTTP methods.

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

const MethodDelete = "DELETE"

Common HTTP methods.

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

const MethodConnect = "CONNECT"

Common HTTP methods.

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

const MethodOptions = "OPTIONS"

Common HTTP methods.

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

const MethodTrace = "TRACE"

Common HTTP methods.

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

const defaultMaxMemory = 32 << 20 // 32 MB
const defaultUserAgent = "Go-http-client/1.1"

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.

const Big = 1000000 // arbitrary upper bound
const prefix = "Basic "
const deleteHostHeader = true

Constants for readRequest's deleteHostHeader parameter.

const keepHostHeader = false

Constants for readRequest's deleteHostHeader parameter.

const bufferBeforeChunkingSize = 2048

This should be >= 512 bytes for DetectContentType, but otherwise it's somewhat arbitrary.

const TrailerPrefix = "Trailer:"

TrailerPrefix is a magic prefix for ResponseWriter.Header map keys that, if present, signals that the map entry is actually for the response trailers, and not the response headers. The prefix is stripped after the ServeHTTP call finishes and the values are sent in the trailers.

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

[https://golang.org/pkg/net/http/#ResponseWriter](https://golang.org/pkg/net/http/#ResponseWriter)
[https://golang.org/pkg/net/http/#example_ResponseWriter_trailers](https://golang.org/pkg/net/http/#example_ResponseWriter_trailers)

const debugServerConnections = false

debugServerConnections controls whether all server connections are wrapped with a verbose logging wrapper.

const DefaultMaxHeaderBytes = 1 << 20 // 1 MB

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

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

TimeFormat is the time format to use when generating times in HTTP headers. It is like time.RFC1123 but hard-codes GMT as the time zone. The time being formatted must be in UTC for Format to generate the correct format.

For parsing this time format, see ParseTime.

const days = "SunMonTueWedThuFriSat"
const months = "JanFebMarAprMayJunJulAugSepOctNovDec"
const maxPostHandlerReadBytes = 256 << 10

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)

const rstAvoidanceDelay = 500 * time.Millisecond

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

const runHooks = true
const skipHooks = false
const size = 64 << 10
const errorHeaders = "\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\n"
const publicErr = "431 Request Header Fields Too Large"

Their HTTP client may or may not be able to read this if we're responding to them and hanging up while they're still writing their request. Undefined behavior.

const shutdownPollIntervalMax = 500 * time.Millisecond

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.

const StateNew ConnState = iota

StateNew represents a new connection that is expected to send a request immediately. Connections begin at this state and then transition to either StateActive or StateClosed.

const StateActive

StateActive represents a connection that has read 1 or more bytes of a request. The Server.ConnState hook for StateActive fires before the request has entered a handler and doesn't fire again until the request has been handled. After the request is handled, the state transitions to StateClosed, StateHijacked, or StateIdle. For HTTP/2, StateActive fires on the transition from zero to one active request, and only transitions away once all active requests are complete. That means that ConnState cannot be used to do per-request work; ConnState only notes the overall state of the connection.

const StateIdle

StateIdle represents a connection that has finished handling a request and is in the keep-alive state, waiting for a new request. Connections transition from StateIdle to either StateActive or StateClosed.

const StateHijacked

StateHijacked represents a hijacked connection. This is a terminal state. It does not transition to StateClosed.

const StateClosed

StateClosed represents a closed connection. This is a terminal state. Hijacked connections do not transition to StateClosed.

const sniffLen = 512

The algorithm uses at most sniffLen bytes to make its decision.

const socksVersion5 = 0x05

Wire protocol constants.

const socksAddrTypeIPv4 = 0x01

Wire protocol constants.

const socksAddrTypeFQDN = 0x03

Wire protocol constants.

const socksAddrTypeIPv6 = 0x04

Wire protocol constants.

const socksCmdConnect socksCommand = 0x01 // establishes an active-open forward proxy connection

Wire protocol constants.

const sockscmdBind socksCommand = 0x02 // establishes a passive-open forward proxy connection

Wire protocol constants.

const socksAuthMethodNotRequired socksAuthMethod = 0x00 // no authentication required

Wire protocol constants.

const socksAuthMethodUsernamePassword socksAuthMethod = 0x02 // use username/password

Wire protocol constants.

const socksAuthMethodNoAcceptableMethods socksAuthMethod = 0xff // no acceptable authentication methods

Wire protocol constants.

const socksStatusSucceeded socksReply = 0x00

Wire protocol constants.

const socksauthUsernamePasswordVersion = 0x01
const socksauthStatusSucceeded = 0x00
const StatusContinue = 100 // RFC 7231, 6.2.1

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

const StatusSwitchingProtocols = 101 // RFC 7231, 6.2.2

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

const StatusProcessing = 102 // RFC 2518, 10.1

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

const StatusEarlyHints = 103 // RFC 8297

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

const StatusOK = 200 // RFC 7231, 6.3.1

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

const StatusCreated = 201 // RFC 7231, 6.3.2

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

const StatusAccepted = 202 // RFC 7231, 6.3.3

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

const StatusNonAuthoritativeInfo = 203 // RFC 7231, 6.3.4

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

const StatusNoContent = 204 // RFC 7231, 6.3.5

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

const StatusResetContent = 205 // RFC 7231, 6.3.6

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

const StatusPartialContent = 206 // RFC 7233, 4.1

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

const StatusMultiStatus = 207 // RFC 4918, 11.1

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

const StatusAlreadyReported = 208 // RFC 5842, 7.1

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

const StatusIMUsed = 226 // RFC 3229, 10.4.1

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

const StatusMultipleChoices = 300 // RFC 7231, 6.4.1

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

const StatusMovedPermanently = 301 // RFC 7231, 6.4.2

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

const StatusFound = 302 // RFC 7231, 6.4.3

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

const StatusSeeOther = 303 // RFC 7231, 6.4.4

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

const StatusNotModified = 304 // RFC 7232, 4.1

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

const StatusUseProxy = 305 // RFC 7231, 6.4.5

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

const _ = 306 // RFC 7231, 6.4.6 (Unused)

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

const StatusTemporaryRedirect = 307 // RFC 7231, 6.4.7

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

const StatusPermanentRedirect = 308 // RFC 7538, 3

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

const StatusBadRequest = 400 // RFC 7231, 6.5.1

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

const StatusUnauthorized = 401 // RFC 7235, 3.1

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

const StatusPaymentRequired = 402 // RFC 7231, 6.5.2

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

const StatusForbidden = 403 // RFC 7231, 6.5.3

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

const StatusNotFound = 404 // RFC 7231, 6.5.4

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

const StatusMethodNotAllowed = 405 // RFC 7231, 6.5.5

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

const StatusNotAcceptable = 406 // RFC 7231, 6.5.6

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

const StatusProxyAuthRequired = 407 // RFC 7235, 3.2

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

const StatusRequestTimeout = 408 // RFC 7231, 6.5.7

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

const StatusConflict = 409 // RFC 7231, 6.5.8

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

const StatusGone = 410 // RFC 7231, 6.5.9

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

const StatusLengthRequired = 411 // RFC 7231, 6.5.10

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

const StatusPreconditionFailed = 412 // RFC 7232, 4.2

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

const StatusRequestEntityTooLarge = 413 // RFC 7231, 6.5.11

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

const StatusRequestURITooLong = 414 // RFC 7231, 6.5.12

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

const StatusUnsupportedMediaType = 415 // RFC 7231, 6.5.13

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

const StatusRequestedRangeNotSatisfiable = 416 // RFC 7233, 4.4

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

const StatusExpectationFailed = 417 // RFC 7231, 6.5.14

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

const StatusTeapot = 418 // RFC 7168, 2.3.3

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

const StatusMisdirectedRequest = 421 // RFC 7540, 9.1.2

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

const StatusUnprocessableEntity = 422 // RFC 4918, 11.2

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

const StatusLocked = 423 // RFC 4918, 11.3

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

const StatusFailedDependency = 424 // RFC 4918, 11.4

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

const StatusTooEarly = 425 // RFC 8470, 5.2.

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

const StatusUpgradeRequired = 426 // RFC 7231, 6.5.15

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

const StatusPreconditionRequired = 428 // RFC 6585, 3

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

const StatusTooManyRequests = 429 // RFC 6585, 4

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

const StatusRequestHeaderFieldsTooLarge = 431 // RFC 6585, 5

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

const StatusUnavailableForLegalReasons = 451 // RFC 7725, 3

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

const StatusInternalServerError = 500 // RFC 7231, 6.6.1

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

const StatusNotImplemented = 501 // RFC 7231, 6.6.2

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

const StatusBadGateway = 502 // RFC 7231, 6.6.3

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

const StatusServiceUnavailable = 503 // RFC 7231, 6.6.4

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

const StatusGatewayTimeout = 504 // RFC 7231, 6.6.5

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

const StatusHTTPVersionNotSupported = 505 // RFC 7231, 6.6.6

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

const StatusVariantAlsoNegotiates = 506 // RFC 2295, 8.1

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

const StatusInsufficientStorage = 507 // RFC 4918, 11.5

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

const StatusLoopDetected = 508 // RFC 5842, 7.2

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

const StatusNotExtended = 510 // RFC 2774, 7

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

const StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6

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

const DefaultMaxIdleConnsPerHost = 2

DefaultMaxIdleConnsPerHost is the default value of Transport's MaxIdleConnsPerHost.

const h2max = 1<<32 - 1
const max1xxResponses = 5 // arbitrary bound on number of informational responses
const maxWriteWaitBeforeConnReuse = 50 * time.Millisecond

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.

const debugRoundTrip = false
const wantCookieString = `cookie-9=i3e01nf61b6t23bvfmplnanol3; Path=/restricted/; Domain=example.com; Expires=Tue, 10 Nov 2009 23:00:00 GMT; Max-Age=3600`
const MaxWriteWaitBeforeConnReuse = maxWriteWaitBeforeConnReuse
const badURL = "file://../no-exist.txt"
const writeCalls = 4 // number of Write calls in current implementation
const shortBody = "Short body, not 123 bytes."
const connectionCloseHeader = "Connection: close"
var DefaultClient = ...

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

var cancelCtx func()
var cancelCtx func()
var once sync.Once
var timedOut atomicBool
var ErrUseLastResponse = errors.New("net/http: use last response")

ErrUseLastResponse can be returned by Client.CheckRedirect hooks to control how redirects are processed. If returned, the next request is not sent and the most recent response is returned with its body unclosed.

var testHookClientDoResult func(retres *Response, reterr error)
var deadline = c.deadline()
var reqs []*Request
var resp *Response
var copyHeaders = c.makeHeadersCopier(req)
var reqBodyClosed = false // have we closed the current req.Body?
var redirectMethod string

Redirect behavior:

var includeBody bool
var urlStr string
var err error
var didTimeout func() bool
var shouldRedirect bool
var ireqhdr = cloneOrMakeHeader(ireq.Header)

The headers to copy are from the very initial request. We use a closured callback to keep a reference to these original headers.

var icookies map[string][]*Cookie

The headers to copy are from the very initial request. We use a closured callback to keep a reference to these original headers.

var changed bool
var ss []string
var b strings.Builder
var buf [len(TimeFormat)]byte
var part string
var cookieNameSanitizer = strings.NewReplacer("\n", "-", "\r", "-")
var dirs anyDirs

Prefer to use ReadDir instead of Readdir, because the former doesn't require calling Stat on every entry of a directory on Unix.

var err error
var list dirEntryDirs
var list fileInfoDirs
var errSeeker = errors.New("seeker can't seek")

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.

var errNoOverlap = errors.New("invalid range: failed to overlap")

errNoOverlap is returned by serveContent's parseRange if first-byte-pos of all of the byte-range-spec values is greater than the content size.

var ctype string
var buf [sniffLen]byte

read a chunk to decide between utf-8 text and binary

var sendContent io.Reader = content
var unixEpochTime = time.Unix(0, 0)
var errMissingSeek = errors.New("io.File missing Seek method")
var errMissingReadDir = errors.New("io.File directory missing ReadDir method")
var list []fs.FileInfo
var ranges []httpRange
var r httpRange
var w countingWriter
var _ http2clientConnPoolIdleCloser = (*http2clientConnPool)(nil)
var _ http2clientConnPoolIdleCloser = ...
var http2dataChunkSizeClasses = ...

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))

var http2dataChunkPools = ...

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))

var http2errReadEmpty = errors.New("read from empty dataBuffer")
var ntotal int
var http2errCodeName = ...
var http2errMixPseudoHeaderTypes = errors.New("mix of request and response pseudo headers")
var http2errPseudoAfterRegular = errors.New("pseudo header field after regular")
var http2padZeros = make([]byte, 255) // zeros for padding
var http2frameName = ...
var http2flagName = ...
var http2frameParsers = ...
var buf bytes.Buffer
var http2fhBytes = ...

frame header bytes. Used only by ReadFrameHeader.

var http2ErrFrameTooLarge = errors.New("http2: frame too large")

ErrFrameTooLarge is returned from Framer.ReadFrame when the peer sends a frame that is larger than declared with SetMaxReadFrameSize.

var padSize byte
var err error
var http2errStreamID = errors.New("invalid stream ID")
var http2errDepStreamID = errors.New("invalid dependent stream ID")
var http2errPadLength = errors.New("pad length too large")
var http2errPadBytes = errors.New("padding bytes must all be zeros unless AllowIllegalWrites is enabled")
var flags http2Flags
var flags http2Flags
var padLength uint8
var v uint32
var flags http2Flags
var flags http2Flags
var padLength uint8

The PUSH_PROMISE frame includes optional padding. Padding fields and flags are identical to those defined for DATA frames

var flags http2Flags
var isRequest, isResponse bool
var isRequest, isResponse bool
var remainSize = fr.maxHeaderListSize()
var sawRegular bool
var invalid error // pseudo header field errors
var hc http2headersOrContinuation = hf
var buf bytes.Buffer
var http2DebugGoroutines = os.Getenv("DEBUG_HTTP2_GOROUTINES") == "1"
var http2goroutineSpace = []byte("goroutine ")
var http2littleBuf = ...
var cutoff, maxVal uint64
var cutoff, maxVal uint64
var v byte
var http2commonBuildOnce sync.Once
var http2commonLowerHeader map[string]string // Go-Canonical-Case -> lower-case
var http2commonCanonHeader map[string]string // lower-case -> Go-Canonical-Case
var http2VerboseLogs bool
var http2logFrameWrites bool
var http2logFrameReads bool
var http2inTests bool
var http2clientPreface = []byte(http2ClientPreface)
var http2stateName = ...
var http2settingName = ...
var http2bufWriterPool = ...
var http2errTimeout error = ...
var http2sorterPool = ...
var http2errClosedPipeWrite = errors.New("write on closed buffer")
var http2errClientDisconnected = errors.New("client disconnected")
var http2errClosedBody = errors.New("body closed by handler")
var http2errHandlerComplete = errors.New("http2: request body closed due to handler exiting")
var http2errStreamClosed = errors.New("http2: stream closed")
var http2responseWriterStatePool = ...
var http2testHookOnConn func()

Test hooks.

var http2testHookGetServerConn func(*http2serverConn)

Test hooks.

var http2testHookOnPanicMu *sync.Mutex // nil except in tests

Test hooks.

var http2testHookOnPanic func(sc *http2serverConn, panicVal interface{}) (rePanic bool)

Test hooks.

var ctx context.Context

The TLSNextProto interface predates contexts, so the net/http package passes down its per-connection base context via an exported but unadvertised method on the Handler. This is for internal net/http<=>http2 use only.

var http2settingsTimerMsg = new(http2serverMessage)

Message values sent to serveMsgCh.

var http2idleTimerMsg = new(http2serverMessage)

Message values sent to serveMsgCh.

var http2shutdownTimerMsg = new(http2serverMessage)

Message values sent to serveMsgCh.

var http2gracefulShutdownMsg = new(http2serverMessage)

Message values sent to serveMsgCh.

var http2errPrefaceTimeout = errors.New("timeout waiting for client preface")
var http2errChanPool = ...
var http2writeDataPool = ...
var frameWriteDone bool // the frame write is done (successfully or not)
var ignoreWrite bool

If true, wr will not be written and wr.done will not be signaled.

var err error
var http2errHandlerPanicked = errors.New("http2: handler panicked")

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.

var http2goAwayTimeout = 1 * time.Second

After sending GOAWAY, 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?

var tlsState *tls.ConnectionState // nil if not scheme https
var trailer Header

Setup Trailers

var url_ *url.URL
var requestURI string
var err error
var errc chan error
var streamID uint32
var ok bool
var _ CloseNotifier = (*http2responseWriter)(nil)

Optional http.ResponseWriter interfaces implemented.

var _ Flusher = (*http2responseWriter)(nil)

Optional http.ResponseWriter interfaces implemented.

var _ http2stringWriter = (*http2responseWriter)(nil)

Optional http.ResponseWriter interfaces implemented.

var ctype, clen string
var ctype, clen string
var date string
var http2ErrRecursivePush = errors.New("http2: recursive push not allowed")

Push errors.

var http2ErrPushLimitReached = errors.New("http2: push would exceed peer's SETTINGS_MAX_CONCURRENT_STREAMS")

Push errors.

var _ Pusher = (*http2responseWriter)(nil)
var http2connHeaders = ...

From http://httpwg.org/specs/rfc7540.html#rfc.section.8.1.2.2

var x interface{} = hs
var http2got1xxFuncForTests func(int, textproto.MIMEHeader) error
var http2ErrNoCachedConn error = ...
var http2errClientConnClosed = errors.New("http2: client conn is closed")
var http2errClientConnUnusable = errors.New("http2: client conn not usable")
var http2errClientConnGotGoAway = errors.New("http2: Transport received Server's graceful shutdown GOAWAY")
var maxConcurrentOkay bool
var http2shutdownEnterWaitStateHook = ...
var http2errRequestCanceled = errors.New("net/http: request canceled")

errRequestCanceled is a copy of net/http's errRequestCanceled because it's not exported. At least they'll be DeepEqual for h1-vs-h2 comparisons tests.

var requestedGzip bool

TODO(bradfitz): this is a copy of the logic in net/http. Unify somewhere?

var respHeaderTimer <-chan time.Time
var waitingForConn chan struct{} = ...
var waitingForConnErr error // guarded by cc.mu
var http2errStopReqBodyWrite = errors.New("http2: aborting request body write")

internal error values; they don't escape to callers

abort request body write; don't send cancel

var http2errStopReqBodyWriteAndCancel = errors.New("http2: canceling request")

internal error values; they don't escape to callers

abort request body write, but send stream reset of cancel.

var http2errReqBodyTooLong = errors.New("http2: request body larger than specified content length")

internal error values; they don't escape to callers

var sawEOF bool
var n1 int

The request body's Content-Length was predeclared and we just finished reading it all, but the underlying io.Reader returned the final chunk with a nil error (which is one of the two valid things a Reader can do at EOF). Because we'd prefer to send the END_STREAM bit early, double-check that we're actually at EOF. Subsequent reads should return (0, EOF) at this point. If either value is different, we return an error in one of two ways below.

var allowed int32
var trls []byte
var path string
var didUA bool
var t *time.Timer
var connAdd, streamAdd int32
var connAdd, streamAdd int32
var http2errClosedResponseBody = errors.New("http2: response body closed")
var refund int

Return any padded flow control now, since we won't refund it later on body reads.

var code func()
var p [8]byte

Generate a random payload

var http2errResponseHeaderListSize = errors.New("http2: response header list larger than advertised limit")
var http2errRequestHeaderListSize = errors.New("http2: request header list larger than peer's advertised limit")
var http2noBody io.ReadCloser = ioutil.NopCloser(bytes.NewReader(nil))
var empty http2FrameWriteRequest
var des string
var n *http2priorityNode
var timeFormats = ...
var headerNewlineToSpace = strings.NewReplacer("\n", " ", "\r", " ")
var headerSorterPool = ...
var formattedVals []string
var aLongTimeAgo = time.Unix(1, 0)

aLongTimeAgo is a non-zero time, far in the past, used for immediate cancellation of network operations.

var omitBundledHTTP2 bool

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.

var NoBody = ...

NoBody is an io.ReadCloser with no bytes. Read always returns EOF and Close always returns nil. It can be used in an outgoing client request to explicitly signal that a request has zero bytes. An alternative, however, is to simply set Request.Body to nil.

var _ io.WriterTo = NoBody

verify that an io.Copy from NoBody won't require a buffer:

var _ io.ReadCloser = NoBody
var ErrMissingFile = errors.New("http: no such file")

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

var ErrNotSupported = ...

ErrNotSupported is returned by the Push method of Pusher implementations to indicate that HTTP/2 Push support is not available.

var ErrUnexpectedTrailer = ...

Deprecated: ErrUnexpectedTrailer is no longer returned by anything in the net/http package. Callers should not compare errors against this variable.

var ErrMissingBoundary = ...

ErrMissingBoundary is returned by Request.MultipartReader when the request's Content-Type does not include a "boundary" parameter.

var ErrNotMultipart = ...

ErrNotMultipart is returned by Request.MultipartReader when the request's Content-Type is not multipart/form-data.

var ErrHeaderTooLong = ...

Deprecated: ErrHeaderTooLong is no longer returned by anything in the net/http package. Callers should not compare errors against this variable.

var ErrShortBody = ...

Deprecated: ErrShortBody is no longer returned by anything in the net/http package. Callers should not compare errors against this variable.

var ErrMissingContentLength = ...

Deprecated: ErrMissingContentLength is no longer returned by anything in the net/http package. Callers should not compare errors against this variable.

var reqWriteExcludeHeader = ...

Headers that Request.Write handles itself and should be skipped.

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

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

var multipartByReader = ...

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.

var errMissingHost = errors.New("http: Request.Write on Request with no Host or URL set")

errMissingHost is returned by Write when there is no Host or URL present in the Request.

var bw *bufio.Writer

Wrap the writer in a bufio Writer if it's not already buffered. Don't always call NewWriter, as that forces a bytes.Buffer and other small bufio Writers to have a minimum 4k buffer size.

var textprotoReaderPool sync.Pool
var s string

First line: GET /index.html HTTP/1.0

var ok bool
var reader io.Reader = r.Body
var err error
var newValues url.Values
var e error
var respExcludeHeader = ...
var ErrNoLocation = errors.New("http: no Location header in response")

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

var ok bool
var ok bool
var buf [1]byte

Is it actually 0 length? Or just unknown?

var ErrBodyNotAllowed = errors.New("http: request method or response status code does not allow body")

Errors used by the HTTP server.

ErrBodyNotAllowed is returned by ResponseWriter.Write calls when the HTTP method or response code does not permit a body.

var ErrHijacked = errors.New("http: connection has been hijacked")

Errors used by the HTTP server.

ErrHijacked is returned by ResponseWriter.Write calls when the underlying connection has been hijacked using the Hijacker interface. A zero-byte write on a hijacked connection will return ErrHijacked without any other side effects.

var ErrContentLength = errors.New("http: wrote more than the declared Content-Length")

Errors used by the HTTP server.

ErrContentLength is returned by ResponseWriter.Write calls when a Handler set a Content-Length response header with a declared size and then attempted to write more bytes than declared.

var ErrWriteAfterFlush = errors.New("unused")

Errors used by the HTTP server.

Deprecated: ErrWriteAfterFlush is no longer returned by anything in the net/http package. Callers should not compare errors against this variable.

var ServerContextKey = ...

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.

var LocalAddrContextKey = ...

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.

var crlf = []byte("\r\n")
var colonSpace = []byte(": ")
var t Header
var bufioReaderPool sync.Pool
var bufioWriter2kPool sync.Pool
var bufioWriter4kPool sync.Pool
var copyBufPool = ...
var errTooLarge = errors.New("http: request too large")
var wholeReqDeadline time.Time // or zero if none
var hdrDeadline time.Time // or zero if none
var frame runtime.Frame
var extraHeaderKeys = ...

Sorted the same as extraHeader.Write's loop.

var headerContentLength = []byte("Content-Length: ")
var headerDate = []byte("Date: ")
var excludeHeader map[string]bool
var setHeader extraHeader
var discard, tooBig bool
var discard, tooBig bool
var _ closeWriter = (*net.TCPConn)(nil)
var ErrAbortHandler = errors.New("net/http: abort Handler")

ErrAbortHandler is a sentinel panic value to abort a handler. While any panic from ServeHTTP aborts the response to the client, panicking with ErrAbortHandler also suppresses logging of a stack trace to the server's error log.

var query string
var htmlReplacer = strings.NewReplacer(
	"&", "&amp;",
	"<", "&lt;",
	">", "&gt;",

	`"`, "&#34;",

	"'", "&#39;",
)
var DefaultServeMux = &defaultServeMux

DefaultServeMux is the default ServeMux used by Serve.

var defaultServeMux ServeMux
var err error
var stateName = ...
var testHookServerServe func(*Server, net.Listener) // used if non-nil
var ErrServerClosed = errors.New("http: Server closed")

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

var tempDelay time.Duration // how long to sleep on accept failure
var err error
var ErrHandlerTimeout = errors.New("http: Handler timeout")

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

var cancelCtx context.CancelFunc
var _ Pusher = (*timeoutWriter)(nil)
var uniqNameMu sync.Mutex
var uniqNameNext = make(map[string]int)
var sniffSignatures = ...

Data matching the table in section 6.

var mp4ftype = []byte("ftyp")
var mp4 = []byte("mp4")
var socksnoDeadline = ...
var socksaLongTimeAgo = time.Unix(1, 0)
var a socksAddr
var err error
var c net.Conn
var dd net.Dialer
var err error
var c net.Conn
var statusText = ...
var ErrLineTooLong = internal.ErrLineTooLong

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

var buf [1]byte
var rres readResult
var ncopy int64
var body = t.unwrapBody()
var nextra int64
var suppressedHeaders304 = ...
var suppressedHeadersNoBody = ...
var cl string

Logic based on Content-Length

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

ErrBodyReadAfterClose is returned when reading a Request or Response Body after the body has been closed. This typically happens when the body is read after an HTTP Handler calls WriteHeader or Write on its ResponseWriter.

var singleCRLF = []byte("\r\n")
var doubleCRLF = []byte("\r\n\r\n")
var errTrailerEOF = errors.New("http: unexpected EOF reading trailer")
var err error
var n int64
var nopCloserType = reflect.TypeOf(io.NopCloser(nil))
var DefaultTransport RoundTripper = ...

DefaultTransport is the default implementation of Transport and is used by DefaultClient. It establishes network connections as needed and caches them for reuse by subsequent calls. It uses HTTP proxies as directed by the $HTTP_PROXY and $NO_PROXY (or $http_proxy and $no_proxy) environment variables.

var err error
var resp *Response
var errCannotRewind = errors.New("net/http: cannot rewind body after connection loss")
var ErrSkipAltProtocol = errors.New("net/http: skip alternate protocol")

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

var envProxyOnce sync.Once

proxyConfigOnce guards proxyConfig

var envProxyFuncValue func(*url.URL) (*url.URL, error)
var errKeepAlivesDisabled = errors.New("http: putIdleConn: keep alives disabled")

error values for debugging and testing, not seen by users.

var errConnBroken = errors.New("http: putIdleConn: connection is in bad state")

error values for debugging and testing, not seen by users.

var errCloseIdle = errors.New("http: putIdleConn: CloseIdleConnections was called")

error values for debugging and testing, not seen by users.

var errTooManyIdle = errors.New("http: putIdleConn: too many idle connections")

error values for debugging and testing, not seen by users.

var errTooManyIdleHost = errors.New("http: putIdleConn: too many idle connections for host")

error values for debugging and testing, not seen by users.

var errCloseIdleConns = errors.New("http: CloseIdleConnections called")

error values for debugging and testing, not seen by users.

var errReadLoopExiting = errors.New("http: persistConn.readLoop exiting")

error values for debugging and testing, not seen by users.

var errIdleConnTimeout = errors.New("http: idle connection timeout")

error values for debugging and testing, not seen by users.

var errServerClosedIdle = errors.New("http: server closed idle connection")

error values for debugging and testing, not seen by 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 golang/go#19943 (comment)

var oldTime time.Time

If IdleConnTimeout is set, calculate the oldest persistConn.idleAt time we're willing to use a cached idle conn.

var removed bool
var zeroDialer net.Dialer
var timer *time.Timer // for canceling TLS handshake
var err error
var firstTLSHost string
var hdr Header
var err error
var resp *Response
var err error // write or read error
var _ io.ReaderFrom = (*persistConnWriter)(nil)
var h1 string

Only used by tests.

var errCallerOwnsConn = errors.New("read loop ending; caller owns writable underlying conn")

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.

var resp *Response
var errTimeout error = ...
var errRequestCanceled = http2errRequestCanceled

errRequestCanceled is set to be identical to the one from h2 to facilitate testing.

var errRequestCanceledConn = errors.New("net/http: request canceled while waiting for connection") // TODO: unify?
var testHookEnterRoundTrip = nop

testHooks. Always non-nil.

var testHookWaitResLoop = nop

testHooks. Always non-nil.

var testHookRoundTripRetried = nop

testHooks. Always non-nil.

var testHookPrePendingDial = nop

testHooks. Always non-nil.

var testHookPostPendingDial = nop

testHooks. Always non-nil.

var testHookMu sync.Locker = fakeLocker{} // guards following

testHooks. Always non-nil.

var testHookReadLoopBeforeNextRead = nop

testHooks. Always non-nil.

var continueCh chan struct{} = ...
var respHeaderTimer <-chan time.Time
var portMap = ...
var errReadOnClosedResBody = errors.New("http: read on closed response body")
var writeSetCookiesTests = ...
var logbuf bytes.Buffer
var addCookieTests = ...
var readSetCookiesTests = ...
var readCookiesTests = ...
var logbuf bytes.Buffer
var logbuf bytes.Buffer
var benchmarkCookieString string
var c []*Cookie
var c []*Cookie
var DefaultUserAgent = defaultUserAgent
var NewLoggingConn = newLoggingConn
var ExportAppendTime = appendTime
var ExportRefererForURL = refererForURL
var ExportServerNewConn = (*Server).newConn
var ExportCloseWriteAndWait = (*conn).closeWriteAndWait
var ExportErrRequestCanceled = errRequestCanceled
var ExportErrRequestCanceledConn = errRequestCanceledConn
var ExportErrServerClosedIdle = errServerClosedIdle
var ExportServeFile = serveFile
var ExportScanETag = scanETag
var ExportHttp2ConfigureServer = http2ConfigureServer
var Export_shouldCopyHeaderOnRedirect = shouldCopyHeaderOnRedirect
var Export_writeStatusLine = writeStatusLine
var Export_is408Message = is408Message
var SetEnterRoundTripHook = hookSetter(&testHookEnterRoundTrip)
var SetRoundTripRetried = hookSetter(&testHookRoundTripRetried)
var ret []string
var ret []string
var headerWriteTests = ...
var buf bytes.Buffer
var parseTimeTests = ...
var hasTokenTests = ...
var testHeader = ...
var buf bytes.Buffer
var got []string
var valuesCount int
var cacheKeysTests = ...
var proxy *url.URL
var ParseRangeTests = ...
var noError = ""
var noBodyStr = ""
var noTrailer Header = nil
var reqTests = ...
var bout bytes.Buffer
var badRequestTests = ...
var reqWriteTests = ...
var braw bytes.Buffer
var praw bytes.Buffer
var wantErr error
var buf bytes.Buffer // records the output

Use the actual Transport code to record what we would send on the wire, but not using TCP. Use a Transport with a custom dialer that returns a fake net.Conn that waits for the full input (and recording it), and then responds with a dummy response.

var respTests = ...
var bout bytes.Buffer
var readResponseCloseInMiddleTests = ...
var buf bytes.Buffer
var wr io.Writer = &buf
var responseLocationTests = ...
var err error
var buf bytes.Buffer
var buf bytes.Buffer
var buf1 bytes.Buffer
var buf2 bytes.Buffer
var braw bytes.Buffer
var _ io.ReaderFrom = (*mockTransferWriter)(nil)
var actualReader reflect.Type
type Client struct {
	// Transport specifies the mechanism by which individual
	// HTTP requests are made.
	// If nil, DefaultTransport is used.
	Transport RoundTripper

	// CheckRedirect specifies the policy for handling redirects.
	// If CheckRedirect is not nil, the client calls it before
	// following an HTTP redirect. The arguments req and via are
	// the upcoming request and the requests made already, oldest
	// first. If CheckRedirect returns an error, the Client's Get
	// method returns both the previous Response (with its Body
	// closed) and CheckRedirect's error (wrapped in a url.Error)
	// instead of issuing the Request req.
	// As a special case, if CheckRedirect returns ErrUseLastResponse,
	// then the most recent response is returned with its body
	// unclosed, along with a nil error.
	//
	// If CheckRedirect is nil, the Client uses its default policy,
	// which is to stop after 10 consecutive requests.
	CheckRedirect func(req *Request, via []*Request) error

	// Jar specifies the cookie jar.
	//
	// The Jar is used to insert relevant cookies into every
	// outbound Request and is updated with the cookie values
	// of every inbound Response. The Jar is consulted for every
	// redirect that the Client follows.
	//
	// If Jar is nil, cookies are only sent if they are explicitly
	// set on the Request.
	Jar CookieJar

	// 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.
	Timeout time.Duration
}

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

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

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

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

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

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

func (c *Client) send(req *Request, deadline time.Time) (resp *Response, didTimeout func() bool, err error)

didTimeout is non-nil only if err != nil.

func (c *Client) deadline() time.Time
func (c *Client) transport() RoundTripper
func (c *Client) Get(url string) (resp *Response, err error)

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

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.

func (c *Client) checkRedirect(req *Request, via []*Request) error

checkRedirect calls either the user's configured CheckRedirect function, or the default.

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

Do sends an HTTP request and returns an HTTP response, following policy (such as redirects, cookies, auth) as configured on the client.

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

If the returned error is nil, the Response will contain a non-nil Body which the user is expected to close. If the Body is not 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 request timed out or was canceled.

func (c *Client) do(req *Request) (retres *Response, reterr error)
func (c *Client) makeHeadersCopier(ireq *Request) func(*Request)

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.

func (c *Client) Post(url, contentType string, body io.Reader) (resp *Response, err error)

Post issues a POST to the specified URL.

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

If the provided body is an io.Closer, it is closed after the request.

To set custom headers, use NewRequest and Client.Do.

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

func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error)

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

The Content-Type header is set to application/x-www-form-urlencoded. To set other headers, use NewRequest and Client.Do.

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

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

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

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

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

func (c *Client) CloseIdleConnections()

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.

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

RoundTripper is an interface representing the ability to execute a single HTTP transaction, obtaining the Response for a given Request.

A RoundTripper must be safe for concurrent use by multiple goroutines.

func NewFileTransport(fs FileSystem) RoundTripper

NewFileTransport returns a new RoundTripper, serving the provided FileSystem. The returned RoundTripper ignores the URL host in its incoming requests, as well as most other properties of the request.

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

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

type canceler interface{ CancelRequest(*Request) }

The first way, used only for RoundTripper implementations written before Go 1.5 or Go 1.6.

type closeIdler interface {
	CloseIdleConnections()
}
type cancelTimerBody struct {
	stop          func() // stops the time.Timer waiting to cancel the request
	rc            io.ReadCloser
	reqDidTimeout func() bool
}

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.

func (b *cancelTimerBody) Read(p []byte) (n int, err error)
func (b *cancelTimerBody) Close() error
type Cookie struct {
	Name  string
	Value string

	Path       string    // optional
	Domain     string    // optional
	Expires    time.Time // optional
	RawExpires string    // for reading cookies only

	// MaxAge=0 means no 'Max-Age' attribute specified.
	// MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'
	// MaxAge>0 means Max-Age attribute present and given in seconds
	MaxAge   int
	Secure   bool
	HttpOnly bool
	SameSite SameSite
	Raw      string
	Unparsed []string // Raw text of unparsed attribute-value pairs
}

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.

func (c *Cookie) String() string

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

type SameSite int

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.

type fileTransport struct {
	fh fileHandler
}

fileTransport implements RoundTripper for the 'file' protocol.

func (t fileTransport) RoundTrip(req *Request) (resp *Response, err error)
type populateResponse struct {
	res          *Response
	ch           chan *Response
	wroteHeader  bool
	hasContent   bool
	sentResponse bool
	pw           *io.PipeWriter
}

populateResponse is a ResponseWriter that populates the *Response in res, and writes its body to a pipe connected to the response body. Once writes begin or finish() is called, the response is sent on ch.

func newPopulateResponseWriter() (*populateResponse, <-chan *Response)
func (pr *populateResponse) finish()
func (pr *populateResponse) sendResponse()
func (pr *populateResponse) Header() Header
func (pr *populateResponse) WriteHeader(code int)
func (pr *populateResponse) Write(p []byte) (n int, err error)
type Dir string

A Dir implements FileSystem using the native file system restricted to a specific directory tree.

While the FileSystem.Open method takes '/'-separated paths, a Dir's string value is a filename on the native file system, not a URL, so it is separated by filepath.Separator, which isn't necessarily '/'.

Note that Dir 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 ".".

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

Open implements FileSystem using os.Open, opening files for reading rooted and relative to the directory d.

type FileSystem interface {
	Open(name string) (File, error)
}

A FileSystem implements access to a collection of named files. The elements in a file path are separated by slash ('/', U+002F) characters, regardless of host operating system convention. See 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.

func FS(fsys fs.FS) FileSystem

FS converts fsys to a FileSystem implementation, for use with FileServer and NewFileTransport.

type File interface {
	io.Closer
	io.Reader
	io.Seeker
	Readdir(count int) ([]fs.FileInfo, error)
	Stat() (fs.FileInfo, error)
}

A File is returned by a FileSystem's Open method and can be served by the FileServer implementation.

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

type anyDirs interface {
	len() int
	name(i int) string
	isDir(i int) bool
}
type fileInfoDirs []fs.FileInfo
func (d fileInfoDirs) len() int
func (d fileInfoDirs) isDir(i int) bool
func (d fileInfoDirs) name(i int) string
type dirEntryDirs []fs.DirEntry
func (d dirEntryDirs) len() int
func (d dirEntryDirs) isDir(i int) bool
func (d dirEntryDirs) name(i int) string
type condResult int

condResult is the result of an HTTP request precondition check. See https://tools.ietf.org/html/rfc7232 section 3.

func checkIfMatch(w ResponseWriter, r *Request) condResult
func checkIfUnmodifiedSince(r *Request, modtime time.Time) condResult
func checkIfNoneMatch(w ResponseWriter, r *Request) condResult
func checkIfModifiedSince(r *Request, modtime time.Time) condResult
func checkIfRange(w ResponseWriter, r *Request, modtime time.Time) condResult
type fileHandler struct {
	root FileSystem
}
func (f *fileHandler) ServeHTTP(w ResponseWriter, r *Request)
type ioFS struct {
	fsys fs.FS
}
func (f ioFS) Open(name string) (File, error)
type ioFile struct {
	file fs.File
}
func (f ioFile) Close() error
func (f ioFile) Read(b []byte) (int, error)
func (f ioFile) Stat() (fs.FileInfo, error)
func (f ioFile) Seek(offset int64, whence int) (int64, error)
func (f ioFile) ReadDir(count int) ([]fs.DirEntry, error)
func (f ioFile) Readdir(count int) ([]fs.FileInfo, error)
type httpRange struct {
	start, length int64
}

httpRange specifies the byte range to be sent to the client.

func (r httpRange) contentRange(size int64) string
func (r httpRange) mimeHeader(contentType string, size int64) textproto.MIMEHeader
type countingWriter int64

countingWriter counts how many bytes have been written to it.

func (w *countingWriter) Write(p []byte) (n int, err error)
type http2ClientConnPool interface {
	GetClientConn(req *Request, addr string) (*http2ClientConn, error)
	MarkDead(*http2ClientConn)
}

ClientConnPool manages a pool of HTTP/2 client connections.

type http2clientConnPoolIdleCloser interface {
	http2ClientConnPool
	closeIdleConnections()
}

clientConnPoolIdleCloser is the interface implemented by ClientConnPool implementations which can close their idle connections.

type http2clientConnPool struct {
	t *http2Transport

	mu sync.Mutex // TODO: maybe switch to RWMutex
	// TODO: add support for sharing conns based on cert names
	// (e.g. share conn for googleapis.com and appspot.com)
	conns        map[string][]*http2ClientConn // key is host:port
	dialing      map[string]*http2dialCall     // currently in-flight dials
	keys         map[*http2ClientConn][]string
	addConnCalls map[string]*http2addConnCall // in-flight addConnIfNeede calls
}

TODO: use singleflight for dialing and addConnCalls?

func (p *http2clientConnPool) GetClientConn(req *Request, addr string) (*http2ClientConn, error)
func (p *http2clientConnPool) shouldTraceGetConn(st http2clientConnIdleState) bool

shouldTraceGetConn reports whether getClientConn should call any ClientTrace.GetConn hook associated with the http.Request.

This complexity is needed to avoid double calls of the GetConn hook during the back-and-forth between net/http and x/net/http2 (when the net/http.Transport is upgraded to also speak http2), as well as support the case where x/net/http2 is being used directly.

func (p *http2clientConnPool) getClientConn(req *Request, addr string, dialOnMiss bool) (*http2ClientConn, error)
func (p *http2clientConnPool) getStartDialLocked(addr string) *http2dialCall

requires p.mu is held.

func (p *http2clientConnPool) addConnIfNeeded(key string, t *http2Transport, c *tls.Conn) (used bool, err error)

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.

func (p *http2clientConnPool) addConnLocked(key string, cc *http2ClientConn)

p.mu must be held

func (p *http2clientConnPool) MarkDead(cc *http2ClientConn)
func (p *http2clientConnPool) closeIdleConnections()
type http2dialCall struct {
	_    http2incomparable
	p    *http2clientConnPool
	done chan struct{}    // closed when done
	res  *http2ClientConn // valid after done is closed
	err  error            // valid after done is closed
}

dialCall is an in-flight Transport dial call to a host.

func (c *http2dialCall) dial(addr string)

run in its own goroutine.

type http2addConnCall struct {
	_    http2incomparable
	p    *http2clientConnPool
	done chan struct{} // closed when done
	err  error
}
func (c *http2addConnCall) run(t *http2Transport, key string, tc *tls.Conn)
type http2noDialClientConnPool struct{ *http2clientConnPool }

noDialClientConnPool is an implementation of http2.ClientConnPool which never dials. We let the HTTP/1.1 client dial and use its TLS connection instead.

func (p http2noDialClientConnPool) GetClientConn(req *Request, addr string) (*http2ClientConn, error)
type http2dataBuffer struct {
	chunks   [][]byte
	r        int   // next byte to read is chunks[0][r]
	w        int   // next byte to write is chunks[len(chunks)-1][w]
	size     int   // total buffered bytes
	expected int64 // we expect at least this many bytes in future Write calls (ignored if <= 0)
}

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.

func (b *http2dataBuffer) Read(p []byte) (int, error)

Read copies bytes from the buffer into p. It is an error to read when no data is available.

func (b *http2dataBuffer) bytesFromFirstChunk() []byte
func (b *http2dataBuffer) Len() int

Len returns the number of bytes of the unread portion of the buffer.

func (b *http2dataBuffer) Write(p []byte) (int, error)

Write appends p to the buffer.

func (b *http2dataBuffer) lastChunkOrAlloc(want int64) []byte
type http2ErrCode uint32

An ErrCode is an unsigned 32-bit error code as defined in the HTTP/2 spec.

func (e http2ErrCode) String() string
type http2ConnectionError http2ErrCode

ConnectionError is an error that results in the termination of the entire connection.

func (e http2ConnectionError) Error() string
type http2StreamError struct {
	StreamID uint32
	Code     http2ErrCode
	Cause    error // optional additional detail
}

StreamError is an error that only affects one stream within an HTTP/2 connection.

func http2streamError(id uint32, code http2ErrCode) http2StreamError
func (e http2StreamError) Error() string
func (se http2StreamError) writeFrame(ctx http2writeContext) error
func (se http2StreamError) staysWithinBuffer(max int) bool
type http2goAwayFlowError struct{}

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

func (http2goAwayFlowError) Error() string
type http2connError struct {
	Code   http2ErrCode // the ConnectionError error code
	Reason string       // additional reason
}

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.

func (e http2connError) Error() string
type http2pseudoHeaderError string
func (e http2pseudoHeaderError) Error() string
type http2duplicatePseudoHeaderError string
func (e http2duplicatePseudoHeaderError) Error() string
type http2headerFieldNameError string
func (e http2headerFieldNameError) Error() string
type http2headerFieldValueError string
func (e http2headerFieldValueError) Error() string
type http2flow struct {
	_ http2incomparable

	// n is the number of DATA bytes we're allowed to send.
	// A flow is kept both on a conn and a per-stream.
	n int32

	// conn points to the shared connection-level flow that is
	// shared by all streams on that conn. It is nil for the flow
	// that's on the conn directly.
	conn *http2flow
}

flow is the flow control window's size.

func (f *http2flow) setConnFlow(cf *http2flow)
func (f *http2flow) available() int32
func (f *http2flow) take(n int32)
func (f *http2flow) add(n int32) bool

add adds n bytes (positive or negative) to the flow control window. It returns false if the sum would exceed 2^31-1.

type http2FrameType uint8

A FrameType is a registered frame type as defined in http://http2.github.io/http2-spec/#rfc.section.11.2

func (t http2FrameType) String() string
type http2Flags uint8

Flags is a bitmask of HTTP/2 flags. The meaning of flags varies depending on the frame type.

func (f http2Flags) Has(v http2Flags) bool

Has reports whether f contains all (0 or more) flags in v.

type http2frameParser func(fc *http2frameCache, fh http2FrameHeader, payload []byte) (http2Frame, error)

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
type http2FrameHeader struct {
	valid bool // caller can access []byte fields in the Frame

	// 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).
	Type http2FrameType

	// Flags are the 1 byte of 8 potential bit flags per frame.
	// They are specific to the frame type.
	Flags http2Flags

	// 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.
	Length uint32

	// StreamID is which stream this frame is for. Certain frames
	// are not stream-specific, in which case this field is 0.
	StreamID uint32
}

A FrameHeader is the 9 byte header of all HTTP/2 frames.

See http://http2.github.io/http2-spec/#FrameHeader

func http2ReadFrameHeader(r io.Reader) (http2FrameHeader, error)

ReadFrameHeader reads 9 bytes from r and returns a FrameHeader. Most users should use Framer.ReadFrame instead.

func http2readFrameHeader(buf []byte, r io.Reader) (http2FrameHeader, error)
func (h http2FrameHeader) Header() http2FrameHeader

Header returns h. It exists so FrameHeaders can be embedded in other specific frame types and implement the Frame interface.

func (h http2FrameHeader) String() string
func (h http2FrameHeader) writeDebug(buf *bytes.Buffer)
func (h *http2FrameHeader) checkValid()
func (h *http2FrameHeader) invalidate()
type http2Frame interface {
	Header() http2FrameHeader

	// invalidate is called by Framer.ReadFrame to make this
	// frame's buffers as being invalid, since the subsequent
	// frame will reuse them.
	invalidate()
}

A Frame is the base interface implemented by all frame types. Callers will generally type-assert the specific frame type: *HeadersFrame, *SettingsFrame, *WindowUpdateFrame, etc.

Frames are only valid until the next call to Framer.ReadFrame.

func http2parseDataFrame(fc *http2frameCache, fh http2FrameHeader, payload []byte) (http2Frame, error)
func http2parseSettingsFrame(_ *http2frameCache, fh http2FrameHeader, p []byte) (http2Frame, error)
func http2parsePingFrame(_ *http2frameCache, fh http2FrameHeader, payload []byte) (http2Frame, error)
func http2parseGoAwayFrame(_ *http2frameCache, fh http2FrameHeader, p []byte) (http2Frame, error)
func http2parseUnknownFrame(_ *http2frameCache, fh http2FrameHeader, p []byte) (http2Frame, error)
func http2parseWindowUpdateFrame(_ *http2frameCache, fh http2FrameHeader, p []byte) (http2Frame, error)
func http2parseHeadersFrame(_ *http2frameCache, fh http2FrameHeader, p []byte) (_ http2Frame, err error)
func http2parsePriorityFrame(_ *http2frameCache, fh http2FrameHeader, payload []byte) (http2Frame, error)
func http2parseRSTStreamFrame(_ *http2frameCache, fh http2FrameHeader, p []byte) (http2Frame, error)
func http2parseContinuationFrame(_ *http2frameCache, fh http2FrameHeader, p []byte) (http2Frame, error)
func http2parsePushPromise(_ *http2frameCache, fh http2FrameHeader, p []byte) (_ http2Frame, err error)
type http2Framer struct {
	r         io.Reader
	lastFrame http2Frame
	errDetail error

	// lastHeaderStream is non-zero if the last frame was an
	// unfinished HEADERS/CONTINUATION.
	lastHeaderStream uint32

	maxReadSize uint32
	headerBuf   [http2frameHeaderLen]byte

	// 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.
	getReadBuf func(size uint32) []byte
	readBuf    []byte // cache for default getReadBuf

	maxWriteSize uint32 // zero means unlimited; TODO: implement

	w    io.Writer
	wbuf []byte

	// 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.
	AllowIllegalWrites bool

	// 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.
	AllowIllegalReads bool

	// ReadMetaHeaders if non-nil causes ReadFrame to merge
	// HEADERS and CONTINUATION frames together and return
	// MetaHeadersFrame instead.
	ReadMetaHeaders *hpack.Decoder

	// 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.
	MaxHeaderListSize uint32

	logReads, logWrites bool

	debugFramer       *http2Framer // only use for logging written writes
	debugFramerBuf    *bytes.Buffer
	debugReadLoggerf  func(string, ...interface{})
	debugWriteLoggerf func(string, ...interface{})

	frameCache *http2frameCache // nil if frames aren't reused (default)
}

A Framer reads and writes Frames.

func http2NewFramer(w io.Writer, r io.Reader) *http2Framer

NewFramer returns a Framer that writes frames to w and reads them from r.

func (fr *http2Framer) maxHeaderListSize() uint32
func (f *http2Framer) startWrite(ftype http2FrameType, flags http2Flags, streamID uint32)
func (f *http2Framer) endWrite() error
func (f *http2Framer) logWrite()
func (f *http2Framer) writeByte(v byte)
func (f *http2Framer) writeBytes(v []byte)
func (f *http2Framer) writeUint16(v uint16)
func (f *http2Framer) writeUint32(v uint32)
func (fr *http2Framer) SetReuseFrames()

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.

func (fr *http2Framer) SetMaxReadFrameSize(v uint32)

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.

func (fr *http2Framer) ErrorDetail() error

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.

func (fr *http2Framer) ReadFrame() (http2Frame, error)

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.

func (fr *http2Framer) connError(code http2ErrCode, reason string) error

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.

func (fr *http2Framer) checkFrameOrder(f http2Frame) error

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.

func (f *http2Framer) WriteData(streamID uint32, endStream bool, data []byte) error

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.

func (f *http2Framer) WriteDataPadded(streamID uint32, endStream bool, data, pad []byte) error

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.

func (f *http2Framer) WriteSettings(settings ...http2Setting) error

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.

func (f *http2Framer) WriteSettingsAck() error

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.

func (f *http2Framer) WritePing(ack bool, data [8]byte) error
func (f *http2Framer) WriteGoAway(maxStreamID uint32, code http2ErrCode, debugData []byte) error
func (f *http2Framer) WriteWindowUpdate(streamID, incr uint32) error

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.

func (f *http2Framer) WriteHeaders(p http2HeadersFrameParam) 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.

func (f *http2Framer) WritePriority(streamID uint32, p http2PriorityParam) 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.

func (f *http2Framer) WriteRSTStream(streamID uint32, code http2ErrCode) error

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.

func (f *http2Framer) WriteContinuation(streamID uint32, endHeaders bool, headerBlockFragment []byte) error

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.

func (f *http2Framer) WritePushPromise(p http2PushPromiseParam) error

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.

func (f *http2Framer) WriteRawFrame(t http2FrameType, flags http2Flags, streamID uint32, payload []byte) error

WriteRawFrame writes a raw frame. This can be used to write extension frames unknown to this package.

func (fr *http2Framer) maxHeaderStringLen() int
func (fr *http2Framer) readMetaFrame(hf *http2HeadersFrame) (*http2MetaHeadersFrame, error)

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.

type http2frameCache struct {
	dataFrame http2DataFrame
}
func (fc *http2frameCache) getDataFrame() *http2DataFrame
type http2DataFrame struct {
	http2FrameHeader
	data []byte
}

A DataFrame conveys arbitrary, variable-length sequences of octets associated with a stream. See http://http2.github.io/http2-spec/#rfc.section.6.1

func (f *http2DataFrame) StreamEnded() bool
func (f *http2DataFrame) Data() []byte

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.

type http2SettingsFrame struct {
	http2FrameHeader
	p []byte
}

A SettingsFrame conveys configuration parameters that affect how endpoints communicate, such as preferences and constraints on peer behavior.

See http://http2.github.io/http2-spec/#SETTINGS

func (f *http2SettingsFrame) IsAck() bool
func (f *http2SettingsFrame) Value(id http2SettingID) (v uint32, ok bool)
func (f *http2SettingsFrame) Setting(i int) http2Setting

Setting returns the setting from the frame at the given 0-based index. The index must be >= 0 and less than f.NumSettings().

func (f *http2SettingsFrame) NumSettings() int
func (f *http2SettingsFrame) HasDuplicates() bool

HasDuplicates reports whether f contains any duplicate setting IDs.

func (f *http2SettingsFrame) ForeachSetting(fn func(http2Setting) error) error

ForeachSetting runs fn for each setting. It stops and returns the first error.

type http2PingFrame struct {
	http2FrameHeader
	Data [8]byte
}

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 http://http2.github.io/http2-spec/#rfc.section.6.7

func (f *http2PingFrame) IsAck() bool
type http2GoAwayFrame struct {
	http2FrameHeader
	LastStreamID uint32
	ErrCode      http2ErrCode
	debugData    []byte
}

A GoAwayFrame informs the remote peer to stop creating streams on this connection. See http://http2.github.io/http2-spec/#rfc.section.6.8

func (f *http2GoAwayFrame) DebugData() []byte

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.

type http2UnknownFrame struct {
	http2FrameHeader
	p []byte
}

An UnknownFrame is the frame type returned when the frame type is unknown or no specific frame type parser exists.

func (f *http2UnknownFrame) Payload() []byte

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.

type http2WindowUpdateFrame struct {
	http2FrameHeader
	Increment uint32 // never read with high bit set
}

A WindowUpdateFrame is used to implement flow control. See http://http2.github.io/http2-spec/#rfc.section.6.9

type http2HeadersFrame struct {
	http2FrameHeader

	// Priority is set if FlagHeadersPriority is set in the FrameHeader.
	Priority http2PriorityParam

	headerFragBuf []byte // not owned
}

A HeadersFrame is used to open a stream and additionally carries a header block fragment.

func (f *http2HeadersFrame) HeaderBlockFragment() []byte
func (f *http2HeadersFrame) HeadersEnded() bool
func (f *http2HeadersFrame) StreamEnded() bool
func (f *http2HeadersFrame) HasPriority() bool
type http2HeadersFrameParam struct {
	// StreamID is the required Stream ID to initiate.
	StreamID uint32
	// BlockFragment is part (or all) of a Header Block.
	BlockFragment []byte

	// 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.
	EndStream bool

	// EndHeaders indicates that this frame contains an entire
	// header block and is not followed by any
	// CONTINUATION frames.
	EndHeaders bool

	// PadLength is the optional number of bytes of zeros to add
	// to this frame.
	PadLength uint8

	// Priority, if non-zero, includes stream priority information
	// in the HEADER frame.
	Priority http2PriorityParam
}

HeadersFrameParam are the parameters for writing a HEADERS frame.

type http2PriorityFrame struct {
	http2FrameHeader
	http2PriorityParam
}

A PriorityFrame specifies the sender-advised priority of a stream. See http://http2.github.io/http2-spec/#rfc.section.6.3

type http2PriorityParam struct {
	// StreamDep is a 31-bit stream identifier for the
	// stream that this stream depends on. Zero means no
	// dependency.
	StreamDep uint32

	// Exclusive is whether the dependency is exclusive.
	Exclusive bool

	// 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."
	Weight uint8
}

PriorityParam are the stream prioritzation parameters.

func (p http2PriorityParam) IsZero() bool
type http2RSTStreamFrame struct {
	http2FrameHeader
	ErrCode http2ErrCode
}

A RSTStreamFrame allows for abnormal termination of a stream. See http://http2.github.io/http2-spec/#rfc.section.6.4

type http2ContinuationFrame struct {
	http2FrameHeader
	headerFragBuf []byte
}

A ContinuationFrame is used to continue a sequence of header block fragments. See http://http2.github.io/http2-spec/#rfc.section.6.10

func (f *http2ContinuationFrame) HeaderBlockFragment() []byte
func (f *http2ContinuationFrame) HeadersEnded() bool
type http2PushPromiseFrame struct {
	http2FrameHeader
	PromiseID     uint32
	headerFragBuf []byte // not owned
}

A PushPromiseFrame is used to initiate a server stream. See http://http2.github.io/http2-spec/#rfc.section.6.6

func (f *http2PushPromiseFrame) HeaderBlockFragment() []byte
func (f *http2PushPromiseFrame) HeadersEnded() bool
type http2PushPromiseParam struct {
	// StreamID is the required Stream ID to initiate.
	StreamID uint32

	// PromiseID is the required Stream ID which this
	// Push Promises
	PromiseID uint32

	// BlockFragment is part (or all) of a Header Block.
	BlockFragment []byte

	// EndHeaders indicates that this frame contains an entire
	// header block and is not followed by any
	// CONTINUATION frames.
	EndHeaders bool

	// PadLength is the optional number of bytes of zeros to add
	// to this frame.
	PadLength uint8
}

PushPromiseParam are the parameters for writing a PUSH_PROMISE frame.

type http2streamEnder interface {
	StreamEnded() bool
}
type http2headersEnder interface {
	HeadersEnded() bool
}
type http2headersOrContinuation interface {
	http2headersEnder
	HeaderBlockFragment() []byte
}
type http2MetaHeadersFrame struct {
	*http2HeadersFrame

	// 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.
	Fields []hpack.HeaderField

	// Truncated is whether the max header list size limit was hit
	// and Fields is incomplete. The hpack decoder state is still
	// valid, however.
	Truncated 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.

func (mh *http2MetaHeadersFrame) PseudoValue(pseudo string) string

PseudoValue returns the given pseudo header field's value. The provided pseudo field should not contain the leading colon.

func (mh *http2MetaHeadersFrame) RegularFields() []hpack.HeaderField

RegularFields returns the regular (non-pseudo) header fields of mh. The caller does not own the returned slice.

func (mh *http2MetaHeadersFrame) PseudoFields() []hpack.HeaderField

PseudoFields returns the pseudo header fields of mh. The caller does not own the returned slice.

func (mh *http2MetaHeadersFrame) checkPseudos() error
type http2goroutineLock uint64
func http2newGoroutineLock() http2goroutineLock
func (g http2goroutineLock) check()
func (g http2goroutineLock) checkNotOn()
type http2streamState int
func (st http2streamState) String() string
type http2Setting struct {
	// ID is which setting is being set.
	// See http://http2.github.io/http2-spec/#SettingValues
	ID http2SettingID

	// Val is the value.
	Val uint32
}

Setting is a setting parameter: which setting it is, and its value.

func (s http2Setting) String() string
func (s http2Setting) Valid() error

Valid reports whether the setting is valid.

type http2SettingID uint16

A SettingID is an HTTP/2 setting as defined in http://http2.github.io/http2-spec/#iana-settings

func (s http2SettingID) String() string
type http2stringWriter interface {
	WriteString(s string) (n int, err error)
}

from pkg io

type http2gate chan struct{}

A gate lets two goroutines coordinate their activities.

func (g http2gate) Done()
func (g http2gate) Wait()
type http2closeWaiter chan struct{}

A closeWaiter is like a sync.WaitGroup but only goes 1 to 0 (open to closed).

func (cw *http2closeWaiter) Init()

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.

func (cw http2closeWaiter) Close()

Close marks the closeWaiter as closed and unblocks any waiters.

func (cw http2closeWaiter) Wait()

Wait waits for the closeWaiter to become closed.

type http2bufferedWriter struct {
	_  http2incomparable
	w  io.Writer     // immutable
	bw *bufio.Writer // non-nil when data is buffered
}

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.

func http2newBufferedWriter(w io.Writer) *http2bufferedWriter
func (w *http2bufferedWriter) Available() int
func (w *http2bufferedWriter) Write(p []byte) (n int, err error)
func (w *http2bufferedWriter) Flush() error
type http2httpError struct {
	_       http2incomparable
	msg     string
	timeout bool
}
func (e *http2httpError) Error() string
func (e *http2httpError) Timeout() bool
func (e *http2httpError) Temporary() bool
type http2connectionStater interface {
	ConnectionState() tls.ConnectionState
}
type http2sorter struct {
	v []string // owned by sorter
}
func (s *http2sorter) Len() int
func (s *http2sorter) Swap(i, j int)
func (s *http2sorter) Less(i, j int) bool
func (s *http2sorter) Keys(h Header) []string

Keys returns the sorted keys of h.

The returned slice is only valid until s used again or returned to its pool.

func (s *http2sorter) SortStrings(ss []string)
type http2incomparable [0]func()

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

type http2pipe struct {
	mu       sync.Mutex
	c        sync.Cond       // c.L lazily initialized to &p.mu
	b        http2pipeBuffer // nil when done reading
	unread   int             // bytes unread when done
	err      error           // read error once empty. non-nil means closed.
	breakErr error           // immediate read error (caller doesn't see rest of b)
	donec    chan struct{}   // closed on error
	readFn   func()          // optional code to run in Read before error
}

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)

func (p *http2pipe) Len() int
func (p *http2pipe) Read(d []byte) (n int, err error)

Read waits until data is available and copies bytes from the buffer into p.

func (p *http2pipe) Write(d []byte) (n int, err error)

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.

func (p *http2pipe) CloseWithError(err error)

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.

func (p *http2pipe) BreakWithError(err error)

BreakWithError causes the next Read (waking up a current blocked Read if needed) to return the provided err immediately, without waiting for unread data.

func (p *http2pipe) closeWithErrorAndCode(err error, fn func())

closeWithErrorAndCode is like CloseWithError but also sets some code to run in the caller's goroutine before returning the error.

func (p *http2pipe) closeWithError(dst *error, err error, fn func())
func (p *http2pipe) closeDoneLocked()

requires p.mu be held.

func (p *http2pipe) Err() error

Err returns the error (if any) first set by BreakWithError or CloseWithError.

func (p *http2pipe) Done() <-chan struct{}

Done returns a channel which is closed if and when this pipe is closed with CloseWithError.

type http2pipeBuffer interface {
	Len() int
	io.Writer
	io.Reader
}
type http2Server struct {
	// 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
	MaxHandlers int

	// 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.
	MaxConcurrentStreams uint32

	// 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.
	MaxReadFrameSize uint32

	// PermitProhibitedCipherSuites, if true, permits the use of
	// cipher suites prohibited by the HTTP/2 spec.
	PermitProhibitedCipherSuites bool

	// 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.
	IdleTimeout time.Duration

	// 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.
	MaxUploadBufferPerConnection int32

	// 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.
	MaxUploadBufferPerStream int32

	// NewWriteScheduler constructs a write scheduler for a connection.
	// If nil, a default scheduler is chosen.
	NewWriteScheduler func() http2WriteScheduler

	// 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.
	state *http2serverInternalState
}

Server is an HTTP/2 server.

func (s *http2Server) initialConnRecvWindowSize() int32
func (s *http2Server) initialStreamRecvWindowSize() int32
func (s *http2Server) maxReadFrameSize() uint32
func (s *http2Server) maxConcurrentStreams() uint32
func (s *http2Server) maxQueuedControlFrames() int

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.

func (s *http2Server) ServeConn(c net.Conn, opts *http2ServeConnOpts)

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.

type http2serverInternalState struct {
	mu          sync.Mutex
	activeConns map[*http2serverConn]struct{}
}
func (s *http2serverInternalState) registerConn(sc *http2serverConn)
func (s *http2serverInternalState) unregisterConn(sc *http2serverConn)
func (s *http2serverInternalState) startGracefulShutdown()
type baseContexter interface {
	BaseContext() context.Context
}
type http2ServeConnOpts struct {
	// Context is the base context to use.
	// If nil, context.Background is used.
	Context context.Context

	// BaseConfig optionally sets the base configuration
	// for values. If nil, defaults are used.
	BaseConfig *Server

	// 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.
	Handler Handler
}

ServeConnOpts are options for the Server.ServeConn method.

func (o *http2ServeConnOpts) context() context.Context
func (o *http2ServeConnOpts) baseConfig() *Server
func (o *http2ServeConnOpts) handler() Handler
type http2serverConn struct {
	// Immutable:
	srv              *http2Server
	hs               *Server
	conn             net.Conn
	bw               *http2bufferedWriter // writing to conn
	handler          Handler
	baseCtx          context.Context
	framer           *http2Framer
	doneServing      chan struct{}               // closed when serverConn.serve ends
	readFrameCh      chan http2readFrameResult   // written by serverConn.readFrames
	wantWriteFrameCh chan http2FrameWriteRequest // from handlers -> serve
	wroteFrameCh     chan http2frameWriteResult  // from writeFrameAsync -> serve, tickles more frame writes
	bodyReadCh       chan http2bodyReadMsg       // from handlers -> serve
	serveMsgCh       chan interface{}            // misc messages & code to send to / run on the serve loop
	flow             http2flow                   // conn-wide (not stream-specific) outbound flow control
	inflow           http2flow                   // conn-wide inbound flow control
	tlsState         *tls.ConnectionState        // shared by all handlers, like net/http
	remoteAddrStr    string
	writeSched       http2WriteScheduler

	// Everything following is owned by the serve loop; use serveG.check():
	serveG                      http2goroutineLock // used to verify funcs are on serve()
	pushEnabled                 bool
	sawFirstSettings            bool // got the initial SETTINGS frame after the preface
	needToSendSettingsAck       bool
	unackedSettings             int    // how many SETTINGS have we sent without ACKs?
	queuedControlFrames         int    // control frames in the writeSched queue
	clientMaxStreams            uint32 // SETTINGS_MAX_CONCURRENT_STREAMS from client (our PUSH_PROMISE limit)
	advMaxStreams               uint32 // our SETTINGS_MAX_CONCURRENT_STREAMS advertised the client
	curClientStreams            uint32 // number of open streams initiated by the client
	curPushedStreams            uint32 // number of open streams initiated by server push
	maxClientStreamID           uint32 // max ever seen from client (odd), or 0 if there have been no client requests
	maxPushPromiseID            uint32 // ID of the last push promise (even), or 0 if there have been no pushes
	streams                     map[uint32]*http2stream
	initialStreamSendWindowSize int32
	maxFrameSize                int32
	headerTableSize             uint32
	peerMaxHeaderListSize       uint32            // zero means unknown (default)
	canonHeader                 map[string]string // http2-lower-case -> Go-Canonical-Case
	writingFrame                bool              // started writing a frame (on serve goroutine or separate)
	writingFrameAsync           bool              // started a frame on its own goroutine but haven't heard back on wroteFrameCh
	needsFrameFlush             bool              // last frame write wasn't a flush
	inGoAway                    bool              // we've started to or sent GOAWAY
	inFrameScheduleLoop         bool              // whether we're in the scheduleFrameWrite loop
	needToSendGoAway            bool              // we need to schedule a GOAWAY frame write
	goAwayCode                  http2ErrCode
	shutdownTimer               *time.Timer // nil until used
	idleTimer                   *time.Timer // nil if unused

	// Owned by the writeFrameAsync goroutine:
	headerWriteBuf bytes.Buffer
	hpackEncoder   *hpack.Encoder

	// Used by startGracefulShutdown.
	shutdownOnce sync.Once
}
func (sc *http2serverConn) rejectConn(err http2ErrCode, debug string)
func (sc *http2serverConn) maxHeaderListSize() uint32
func (sc *http2serverConn) curOpenStreams() uint32
func (sc *http2serverConn) Framer() *http2Framer
func (sc *http2serverConn) CloseConn() error
func (sc *http2serverConn) Flush() error
func (sc *http2serverConn) HeaderEncoder() (*hpack.Encoder, *bytes.Buffer)
func (sc *http2serverConn) state(streamID uint32) (http2streamState, *http2stream)
func (sc *http2serverConn) setConnState(state ConnState)

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.

func (sc *http2serverConn) vlogf(format string, args ...interface{})
func (sc *http2serverConn) logf(format string, args ...interface{})
func (sc *http2serverConn) condlogf(err error, format string, args ...interface{})
func (sc *http2serverConn) canonicalHeader(v string) string
func (sc *http2serverConn) readFrames()

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.

func (sc *http2serverConn) writeFrameAsync(wr http2FrameWriteRequest)

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.

func (sc *http2serverConn) closeAllStreamsOnConnClose()
func (sc *http2serverConn) stopShutdownTimer()
func (sc *http2serverConn) notePanic()
func (sc *http2serverConn) serve()
func (sc *http2serverConn) awaitGracefulShutdown(sharedCh <-chan struct{}, privateCh chan struct{})
func (sc *http2serverConn) onSettingsTimer()
func (sc *http2serverConn) onIdleTimer()
func (sc *http2serverConn) onShutdownTimer()
func (sc *http2serverConn) sendServeMsg(msg interface{})
func (sc *http2serverConn) readPreface() error

readPreface reads the ClientPreface greeting from the peer or returns errPrefaceTimeout on timeout, or an error if the greeting is invalid.

func (sc *http2serverConn) writeDataFromHandler(stream *http2stream, data []byte, endStream bool) error

writeDataFromHandler writes DATA response frames from a handler on the given stream.

func (sc *http2serverConn) writeFrameFromHandler(wr http2FrameWriteRequest) error

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.

func (sc *http2serverConn) writeFrame(wr http2FrameWriteRequest)

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.

func (sc *http2serverConn) startFrameWrite(wr http2FrameWriteRequest)

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.

func (sc *http2serverConn) wroteFrame(res http2frameWriteResult)

wroteFrame is called on the serve goroutine with the result of whatever happened on writeFrameAsync.

func (sc *http2serverConn) scheduleFrameWrite()

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.

func (sc *http2serverConn) startGracefulShutdown()

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.

func (sc *http2serverConn) startGracefulShutdownInternal()
func (sc *http2serverConn) goAway(code http2ErrCode)
func (sc *http2serverConn) shutDownIn(d time.Duration)
func (sc *http2serverConn) resetStream(se http2StreamError)
func (sc *http2serverConn) processFrameFromReader(res http2readFrameResult) bool

processFrameFromReader processes the serve loop's read from readFrameCh from the frame-reading goroutine. processFrameFromReader returns whether the connection should be kept open.

func (sc *http2serverConn) processFrame(f http2Frame) error
func (sc *http2serverConn) processPing(f *http2PingFrame) error
func (sc *http2serverConn) processWindowUpdate(f *http2WindowUpdateFrame) error
func (sc *http2serverConn) processResetStream(f *http2RSTStreamFrame) error
func (sc *http2serverConn) closeStream(st *http2stream, err error)
func (sc *http2serverConn) processSettings(f *http2SettingsFrame) error
func (sc *http2serverConn) processSetting(s http2Setting) error
func (sc *http2serverConn) processSettingInitialWindowSize(val uint32) error
func (sc *http2serverConn) processData(f *http2DataFrame) error
func (sc *http2serverConn) processGoAway(f *http2GoAwayFrame) error
func (sc *http2serverConn) processHeaders(f *http2MetaHeadersFrame) error
func (sc *http2serverConn) processPriority(f *http2PriorityFrame) error
func (sc *http2serverConn) newStream(id, pusherID uint32, state http2streamState) *http2stream
func (sc *http2serverConn) newWriterAndRequest(st *http2stream, f *http2MetaHeadersFrame) (*http2responseWriter, *Request, error)
func (sc *http2serverConn) newWriterAndRequestNoBody(st *http2stream, rp http2requestParam) (*http2responseWriter, *Request, error)
func (sc *http2serverConn) runHandler(rw *http2responseWriter, req *Request, handler func(ResponseWriter, *Request))

Run on its own goroutine.

func (sc *http2serverConn) writeHeaders(st *http2stream, headerData *http2writeResHeaders) error

called from handler goroutines. h may be nil.

func (sc *http2serverConn) write100ContinueHeaders(st *http2stream)

called from handler goroutines.

func (sc *http2serverConn) noteBodyReadFromHandler(st *http2stream, n int, err error)

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.

func (sc *http2serverConn) noteBodyRead(st *http2stream, n int)
func (sc *http2serverConn) sendWindowUpdate(st *http2stream, n int)

st may be nil for conn-level

func (sc *http2serverConn) sendWindowUpdate32(st *http2stream, n int32)

st may be nil for conn-level

func (sc *http2serverConn) startPush(msg *http2startPushRequest)
type http2stream struct {
	// immutable:
	sc        *http2serverConn
	id        uint32
	body      *http2pipe       // non-nil if expecting DATA frames
	cw        http2closeWaiter // closed wait stream transitions to closed state
	ctx       context.Context
	cancelCtx func()

	// owned by serverConn's serve loop:
	bodyBytes        int64     // body bytes seen so far
	declBodyBytes    int64     // or -1 if undeclared
	flow             http2flow // limits writing from Handler to client
	inflow           http2flow // what the client is allowed to POST/etc to us
	state            http2streamState
	resetQueued      bool        // RST_STREAM queued for write; set by sc.resetStream
	gotTrailerHeader bool        // HEADER frame for trailers was seen
	wroteHeaders     bool        // whether we wrote headers (not status 100)
	writeDeadline    *time.Timer // nil if unused

	trailer    Header // accumulated trailers
	reqTrailer Header // handler's Request.Trailer
}

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.

func (st *http2stream) isPushed() bool

isPushed reports whether the stream is server-initiated.

func (st *http2stream) endStream()

endStream closes a Request.Body's pipe. It is called when a DATA frame says a request body is over (or after trailers).

func (st *http2stream) copyTrailersToHandlerRequest()

copyTrailersToHandlerRequest is run in the Handler's goroutine in its Request.Body.Read just before it gets io.EOF.

func (st *http2stream) onWriteTimeout()

onWriteTimeout is run on its own goroutine (from time.AfterFunc) when the stream's WriteTimeout has fired.

func (st *http2stream) processTrailerHeaders(f *http2MetaHeadersFrame) error
type http2readFrameResult struct {
	f   http2Frame // valid until readMore is called
	err error

	// readMore should be called once the consumer no longer needs or
	// retains f. After readMore, f is invalid and more frames can be
	// read.
	readMore func()
}
type http2frameWriteResult struct {
	_   http2incomparable
	wr  http2FrameWriteRequest // what was written (or attempted)
	err error                  // result of the writeFrame call
}

frameWriteResult is the message passed from writeFrameAsync to the serve goroutine.

type http2serverMessage int
type http2requestParam struct {
	method                  string
	scheme, authority, path string
	header                  Header
}
type http2bodyReadMsg struct {
	st *http2stream
	n  int
}

A bodyReadMsg tells the server loop that the http.Handler read n bytes of the DATA from the client on the given stream.

type http2requestBody struct {
	_             http2incomparable
	stream        *http2stream
	conn          *http2serverConn
	closed        bool       // for use by Close only
	sawEOF        bool       // for use by Read only
	pipe          *http2pipe // non-nil if we have a HTTP entity message body
	needsContinue bool       // need to send a 100-continue
}

requestBody is the Handler's Request.Body type. Read and Close may be called concurrently.

func (b *http2requestBody) Close() error
func (b *http2requestBody) Read(p []byte) (n int, err error)
type http2responseWriter struct {
	rws *http2responseWriterState
}

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.

func (w *http2responseWriter) Flush()
func (w *http2responseWriter) CloseNotify() <-chan bool
func (w *http2responseWriter) Header() Header
func (w *http2responseWriter) WriteHeader(code int)
func (w *http2responseWriter) Write(p []byte) (n int, err 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)
func (w *http2responseWriter) WriteString(s string) (n int, err error)
func (w *http2responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error)

either dataB or dataS is non-zero.

func (w *http2responseWriter) handlerDone()
func (w *http2responseWriter) Push(target string, opts *PushOptions) error
type http2responseWriterState struct {
	// immutable within a request:
	stream *http2stream
	req    *Request
	body   *http2requestBody // to close at end of request, if DATA frames didn't
	conn   *http2serverConn

	// TODO: adjust buffer writing sizes based on server config, frame size updates from peer, etc
	bw *bufio.Writer // writing to a chunkWriter{this *responseWriterState}

	// mutated by http.Handler goroutine:
	handlerHeader Header   // nil until called
	snapHeader    Header   // snapshot of handlerHeader at WriteHeader time
	trailers      []string // set in writeChunk
	status        int      // status code passed to WriteHeader
	wroteHeader   bool     // WriteHeader called (explicitly or implicitly). Not necessarily sent to user yet.
	sentHeader    bool     // have we sent the header frame?
	handlerDone   bool     // handler has finished
	dirty         bool     // a Write failed; don't reuse this responseWriterState

	sentContentLen int64 // non-zero if handler set a Content-Length header
	wroteBytes     int64

	closeNotifierMu sync.Mutex // guards closeNotifierCh
	closeNotifierCh chan bool  // nil until first used
}
func (rws *http2responseWriterState) hasTrailers() bool
func (rws *http2responseWriterState) hasNonemptyTrailers() bool
func (rws *http2responseWriterState) declareTrailer(k string)

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.

func (rws *http2responseWriterState) writeChunk(p []byte) (n int, err error)

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.

func (rws *http2responseWriterState) promoteUndeclaredTrailers()

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.

func (rws *http2responseWriterState) writeHeader(code int)
type http2chunkWriter struct{ rws *http2responseWriterState }
func (cw http2chunkWriter) Write(p []byte) (n int, err error)
type http2startPushRequest struct {
	parent *http2stream
	method string
	url    *url.URL
	header Header
	done   chan error
}
type I interface {
	doKeepAlives() bool
}
type http2Transport struct {
	// DialTLS specifies an optional dial function for creating
	// TLS connections for requests.
	//
	// If 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.
	DialTLS func(network, addr string, cfg *tls.Config) (net.Conn, error)

	// TLSClientConfig specifies the TLS configuration to use with
	// tls.Client. If nil, the default configuration is used.
	TLSClientConfig *tls.Config

	// ConnPool optionally specifies an alternate connection pool to use.
	// If nil, the default is used.
	ConnPool http2ClientConnPool

	// 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.
	DisableCompression bool

	// AllowHTTP, if true, permits HTTP/2 requests using the insecure,
	// plain-text "http" scheme. Note that this does not enable h2c support.
	AllowHTTP bool

	// 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.
	MaxHeaderListSize uint32

	// 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.
	StrictMaxConcurrentStreams bool

	// 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.
	ReadIdleTimeout time.Duration

	// PingTimeout is the timeout after which the connection will be closed
	// if a response to Ping is not received.
	// Defaults to 15s.
	PingTimeout time.Duration

	// t1, if non-nil, is the standard library Transport using
	// this transport. Its settings are used (but not its
	// RoundTrip method, etc).
	t1 *Transport

	connPoolOnce  sync.Once
	connPoolOrDef http2ClientConnPool // non-nil version of ConnPool
}

Transport is an HTTP/2 Transport.

A Transport internally caches connections to servers. It is safe for concurrent use by multiple goroutines.

func http2ConfigureTransports(t1 *Transport) (*http2Transport, error)

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.

func http2configureTransports(t1 *Transport) (*http2Transport, error)
func (t *http2Transport) maxHeaderListSize() uint32
func (t *http2Transport) disableCompression() bool
func (t *http2Transport) pingTimeout() time.Duration
func (t *http2Transport) connPool() http2ClientConnPool
func (t *http2Transport) initConnPool()
func (t *http2Transport) RoundTrip(req *Request) (*Response, error)
func (t *http2Transport) RoundTripOpt(req *Request, opt http2RoundTripOpt) (*Response, error)

RoundTripOpt is like RoundTrip, but takes options.

func (t *http2Transport) CloseIdleConnections()

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.

func (t *http2Transport) dialClientConn(addr string, singleUse bool) (*http2ClientConn, error)
func (t *http2Transport) newTLSConfig(host string) *tls.Config
func (t *http2Transport) dialTLS() func(string, string, *tls.Config) (net.Conn, error)
func (t *http2Transport) dialTLSDefault(network, addr string, cfg *tls.Config) (net.Conn, error)
func (t *http2Transport) disableKeepAlives() bool

disableKeepAlives reports whether connections should be closed as soon as possible after handling the first request.

func (t *http2Transport) expectContinueTimeout() time.Duration
func (t *http2Transport) NewClientConn(c net.Conn) (*http2ClientConn, error)
func (t *http2Transport) newClientConn(c net.Conn, singleUse bool) (*http2ClientConn, error)
func (t *http2Transport) vlogf(format string, args ...interface{})
func (t *http2Transport) logf(format string, args ...interface{})
func (t *http2Transport) getBodyWriterState(cs *http2clientStream, body io.Reader) (s http2bodyWriterState)
func (t *http2Transport) idleConnTimeout() time.Duration
type http2ClientConn struct {
	t         *http2Transport
	tconn     net.Conn             // usually *tls.Conn, except specialized impls
	tlsState  *tls.ConnectionState // nil only for specialized impls
	reused    uint32               // whether conn is being reused; atomic
	singleUse bool                 // whether being used for a single http.Request

	// readLoop goroutine fields:
	readerDone chan struct{} // closed on error
	readerErr  error         // set before readerDone is closed

	idleTimeout time.Duration // or 0 for never
	idleTimer   *time.Timer

	mu              sync.Mutex // guards following
	cond            *sync.Cond // hold mu; broadcast on flow/closed changes
	flow            http2flow  // our conn-level flow control quota (cs.flow is per stream)
	inflow          http2flow  // peer's conn-level flow control
	closing         bool
	closed          bool
	wantSettingsAck bool                          // we sent a SETTINGS frame and haven't heard back
	goAway          *http2GoAwayFrame             // if non-nil, the GoAwayFrame we received
	goAwayDebug     string                        // goAway frame's debug data, retained as a string
	streams         map[uint32]*http2clientStream // client-initiated
	nextStreamID    uint32
	pendingRequests int                       // requests blocked and waiting to be sent because len(streams) == maxConcurrentStreams
	pings           map[[8]byte]chan struct{} // in flight ping data to notification channel
	bw              *bufio.Writer
	br              *bufio.Reader
	fr              *http2Framer
	lastActive      time.Time
	lastIdle        time.Time // time last idle
	// Settings from peer: (also guarded by mu)
	maxFrameSize          uint32
	maxConcurrentStreams  uint32
	peerMaxHeaderListSize uint64
	initialWindowSize     uint32

	hbuf    bytes.Buffer // HPACK encoder writes into this
	henc    *hpack.Encoder
	freeBuf [][]byte

	wmu  sync.Mutex // held while writing; acquire AFTER mu if holding both
	werr error      // first write error that has occurred
}

ClientConn is the state of a single HTTP/2 client connection to an HTTP/2 server.

func (cc *http2ClientConn) healthCheck()
func (cc *http2ClientConn) setGoAway(f *http2GoAwayFrame)
func (cc *http2ClientConn) CanTakeNewRequest() bool

CanTakeNewRequest reports whether the connection can take a new request, meaning it has not been closed or received or sent a GOAWAY.

func (cc *http2ClientConn) idleState() http2clientConnIdleState
func (cc *http2ClientConn) idleStateLocked() (st http2clientConnIdleState)
func (cc *http2ClientConn) canTakeNewRequestLocked() bool
func (cc *http2ClientConn) tooIdleLocked() bool

tooIdleLocked reports whether this connection has been been sitting idle for too much wall time.

func (cc *http2ClientConn) onIdleTimeout()

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.

func (cc *http2ClientConn) closeIfIdle()
func (cc *http2ClientConn) Shutdown(ctx context.Context) error

Shutdown gracefully close the client connection, waiting for running streams to complete.

func (cc *http2ClientConn) sendGoAway() error
func (cc *http2ClientConn) closeForError(err error) error

closes the client connection immediately. In-flight requests are interrupted. err is sent to streams.

func (cc *http2ClientConn) Close() error

Close closes the client connection immediately.

In-flight requests are interrupted. For a graceful shutdown, use Shutdown instead.

func (cc *http2ClientConn) closeForLostPing() error

closes the client connection immediately. In-flight requests are interrupted.

func (cc *http2ClientConn) frameScratchBuffer() []byte

frameBuffer returns a scratch buffer suitable for writing DATA frames. They're capped at the min of the peer's max frame size or 512KB (kinda arbitrarily), but definitely capped so we don't allocate 4GB bufers.

func (cc *http2ClientConn) putFrameScratchBuffer(buf []byte)
func (cc *http2ClientConn) responseHeaderTimeout() time.Duration
func (cc *http2ClientConn) RoundTrip(req *Request) (*Response, error)
func (cc *http2ClientConn) roundTrip(req *Request) (res *Response, gotErrAfterReqBodyWrite bool, err error)
func (cc *http2ClientConn) awaitOpenSlotForRequest(req *Request) error

awaitOpenSlotForRequest waits until len(streams) < maxConcurrentStreams. Must hold cc.mu.

func (cc *http2ClientConn) writeHeaders(streamID uint32, endStream bool, maxFrameSize int, hdrs []byte) error

requires cc.wmu be held

func (cc *http2ClientConn) encodeHeaders(req *Request, addGzipHeader bool, trailers string, contentLength int64) ([]byte, error)

requires cc.mu be held.

func (cc *http2ClientConn) encodeTrailers(req *Request) ([]byte, error)

requires cc.mu be held.

func (cc *http2ClientConn) writeHeader(name, value string)
func (cc *http2ClientConn) newStream() *http2clientStream

requires cc.mu be held.

func (cc *http2ClientConn) forgetStreamID(id uint32)
func (cc *http2ClientConn) streamByID(id uint32, andRemove bool) *http2clientStream
func (cc *http2ClientConn) readLoop()

readLoop runs in its own goroutine and reads and dispatches frames.

func (cc *http2ClientConn) Ping(ctx context.Context) error

Ping sends a PING frame to the server and waits for the ack.

func (cc *http2ClientConn) writeStreamReset(streamID uint32, code http2ErrCode, err error)
func (cc *http2ClientConn) logf(format string, args ...interface{})
func (cc *http2ClientConn) vlogf(format string, args ...interface{})
type http2clientStream struct {
	cc            *http2ClientConn
	req           *Request
	trace         *httptrace.ClientTrace // or nil
	ID            uint32
	resc          chan http2resAndError
	bufPipe       http2pipe // buffered pipe with the flow-controlled response payload
	startedWrite  bool      // started request body write; guarded by cc.mu
	requestedGzip bool
	on100         func() // optional code to run if get a 100 continue response

	flow        http2flow // guarded by cc.mu
	inflow      http2flow // guarded by cc.mu
	bytesRemain int64     // -1 means unknown; owned by transportResponseBody.Read
	readErr     error     // sticky read error; owned by transportResponseBody.Read
	stopReqBody error     // if non-nil, stop writing req body; guarded by cc.mu
	didReset    bool      // whether we sent a RST_STREAM to the server; guarded by cc.mu

	peerReset chan struct{} // closed on peer reset
	resetErr  error         // populated before peerReset is closed

	done chan struct{} // closed when stream remove from cc.streams map; close calls guarded by cc.mu

	// owned by clientConnReadLoop:
	firstByte    bool  // got the first response byte
	pastHeaders  bool  // got first MetaHeadersFrame (actual headers)
	pastTrailers bool  // got optional second MetaHeadersFrame (trailers)
	num1xx       uint8 // number of 1xx responses seen

	trailer    Header  // accumulated trailers
	resTrailer *Header // client's Response.Trailer
}

clientStream is the state for a single HTTP/2 stream. One of these is created for each Transport.RoundTrip call.

func (cs *http2clientStream) get1xxTraceFunc() func(int, textproto.MIMEHeader) error

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.

func (cs *http2clientStream) awaitRequestCancel(req *Request)

awaitRequestCancel waits for the user to cancel a request, its context to expire, or for the request to be done (any way it might be removed from the cc.streams map: peer reset, successful completion, TCP connection breakage, etc). If the request is canceled, then cs will be canceled and closed.

func (cs *http2clientStream) cancelStream()
func (cs *http2clientStream) checkResetOrDone() error

checkResetOrDone reports any error sent in a RST_STREAM frame by the server, or errStreamClosed if the stream is complete.

func (cs *http2clientStream) getStartedWrite() bool
func (cs *http2clientStream) abortRequestBodyWrite(err error)
func (cs *http2clientStream) writeRequestBody(body io.Reader, bodyCloser io.Closer) (err error)
func (cs *http2clientStream) awaitFlowControl(maxBytes int) (taken int32, 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.

func (cs *http2clientStream) copyTrailers()
type http2stickyErrWriter struct {
	w   io.Writer
	err *error
}
func (sew http2stickyErrWriter) Write(p []byte) (n int, err error)
type http2noCachedConnError struct{}

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.

func (http2noCachedConnError) IsHTTP2NoCachedConnError()
func (http2noCachedConnError) Error() string
type http2RoundTripOpt struct {
	// OnlyCachedConn controls whether RoundTripOpt may
	// create a new TCP connection. If set true and
	// no cached connection is available, RoundTripOpt
	// will return ErrNoCachedConn.
	OnlyCachedConn bool
}

RoundTripOpt are options for the Transport.RoundTripOpt method.

type http2clientConnIdleState struct {
	canTakeNewRequest bool
	freshConn         bool // whether it's unused by any previous request
}

clientConnIdleState describes the suitability of a client connection to initiate a new RoundTrip request.

type http2resAndError struct {
	_   http2incomparable
	res *Response
	err error
}
type http2clientConnReadLoop struct {
	_             http2incomparable
	cc            *http2ClientConn
	closeWhenIdle bool
}

clientConnReadLoop is the state owned by the clientConn's frame-reading readLoop.

func (rl *http2clientConnReadLoop) cleanup()
func (rl *http2clientConnReadLoop) run() error
func (rl *http2clientConnReadLoop) processHeaders(f *http2MetaHeadersFrame) error
func (rl *http2clientConnReadLoop) handleResponse(cs *http2clientStream, f *http2MetaHeadersFrame) (*Response, error)

may return error types nil, or ConnectionError. Any other error value is a StreamError of type ErrCodeProtocol. The returned error in that case is the detail.

As a special case, handleResponse may return (nil, nil) to skip the frame (currently only used for 1xx responses).

func (rl *http2clientConnReadLoop) processTrailers(cs *http2clientStream, f *http2MetaHeadersFrame) error
func (rl *http2clientConnReadLoop) processData(f *http2DataFrame) error
func (rl *http2clientConnReadLoop) endStream(cs *http2clientStream)
func (rl *http2clientConnReadLoop) endStreamError(cs *http2clientStream, err error)
func (rl *http2clientConnReadLoop) processGoAway(f *http2GoAwayFrame) error
func (rl *http2clientConnReadLoop) processSettings(f *http2SettingsFrame) error
func (rl *http2clientConnReadLoop) processWindowUpdate(f *http2WindowUpdateFrame) error
func (rl *http2clientConnReadLoop) processResetStream(f *http2RSTStreamFrame) error
func (rl *http2clientConnReadLoop) processPing(f *http2PingFrame) error
func (rl *http2clientConnReadLoop) processPushPromise(f *http2PushPromiseFrame) error
type http2GoAwayError struct {
	LastStreamID uint32
	ErrCode      http2ErrCode
	DebugData    string
}

GoAwayError is returned by the Transport when the server closes the TCP connection after sending a GOAWAY frame.

func (e http2GoAwayError) Error() string
type http2transportResponseBody struct {
	cs *http2clientStream
}

transportResponseBody is the concrete type of Transport.RoundTrip's Response.Body. It is an io.ReadCloser. On Read, it reads from cs.body. On Close it sends RST_STREAM if EOF wasn't already seen.

func (b http2transportResponseBody) Read(p []byte) (n int, err error)
func (b http2transportResponseBody) Close() error
type http2erringRoundTripper struct{ err error }
func (rt http2erringRoundTripper) RoundTripErr() error
func (rt http2erringRoundTripper) RoundTrip(*Request) (*Response, error)
type http2gzipReader struct {
	_    http2incomparable
	body io.ReadCloser // underlying Response.Body
	zr   *gzip.Reader  // lazily-initialized gzip reader
	zerr error         // sticky error
}

gzipReader wraps a response body so it can lazily call gzip.NewReader on the first call to Read

func (gz *http2gzipReader) Read(p []byte) (n int, err error)
func (gz *http2gzipReader) Close() error
type http2errorReader struct{ err error }
func (r http2errorReader) Read(p []byte) (int, error)
type http2bodyWriterState struct {
	cs     *http2clientStream
	timer  *time.Timer   // if non-nil, we're doing a delayed write
	fnonce *sync.Once    // to call fn with
	fn     func()        // the code to run in the goroutine, writing the body
	resc   chan error    // result of fn's execution
	delay  time.Duration // how long we should delay a delayed write for
}

bodyWriterState encapsulates various state around the Transport's writing of the request body, particularly regarding doing delayed writes of the body when the request contains "Expect: 100-continue".

func (s http2bodyWriterState) cancel()
func (s http2bodyWriterState) on100()
func (s http2bodyWriterState) scheduleBodyWrite()

scheduleBodyWrite starts writing the body, either immediately (in the common case) or after the delay timeout. It should not be called until after the headers have been written.

type http2noDialH2RoundTripper struct{ *http2Transport }

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)

func (rt http2noDialH2RoundTripper) RoundTrip(req *Request) (*Response, error)
type http2writeFramer interface {
	writeFrame(http2writeContext) error

	// staysWithinBuffer reports whether this writer promises that
	// it will only write less than or equal to size bytes, and it
	// won't Flush the write context.
	staysWithinBuffer(size int) bool
}

writeFramer is implemented by any type that is used to write frames.

type http2writeContext interface {
	Framer() *http2Framer
	Flush() error
	CloseConn() error
	// HeaderEncoder returns an HPACK encoder that writes to the
	// returned buffer.
	HeaderEncoder() (*hpack.Encoder, *bytes.Buffer)
}

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.

type http2flushFrameWriter struct{}
func (http2flushFrameWriter) writeFrame(ctx http2writeContext) error
func (http2flushFrameWriter) staysWithinBuffer(max int) bool
type http2writeSettings []http2Setting
func (s http2writeSettings) staysWithinBuffer(max int) bool
func (s http2writeSettings) writeFrame(ctx http2writeContext) error
type http2writeGoAway struct {
	maxStreamID uint32
	code        http2ErrCode
}
func (p *http2writeGoAway) writeFrame(ctx http2writeContext) error
func (*http2writeGoAway) staysWithinBuffer(max int) bool
type http2writeData struct {
	streamID  uint32
	p         []byte
	endStream bool
}
func (w *http2writeData) String() string
func (w *http2writeData) writeFrame(ctx http2writeContext) error
func (w *http2writeData) staysWithinBuffer(max int) bool
type http2handlerPanicRST struct {
	StreamID uint32
}

handlerPanicRST is the message sent from handler goroutines when the handler panics.

func (hp http2handlerPanicRST) writeFrame(ctx http2writeContext) error
func (hp http2handlerPanicRST) staysWithinBuffer(max int) bool
type http2writePingAck struct{ pf *http2PingFrame }
func (w http2writePingAck) writeFrame(ctx http2writeContext) error
func (w http2writePingAck) staysWithinBuffer(max int) bool
type http2writeSettingsAck struct{}
func (http2writeSettingsAck) writeFrame(ctx http2writeContext) error
func (http2writeSettingsAck) staysWithinBuffer(max int) bool
type http2writeResHeaders struct {
	streamID    uint32
	httpResCode int      // 0 means no ":status" line
	h           Header   // may be nil
	trailers    []string // if non-nil, which keys of h to write. nil means all.
	endStream   bool

	date          string
	contentType   string
	contentLength string
}

writeResHeaders is a request to write a HEADERS and 0+ CONTINUATION frames for HTTP response headers or trailers from a server handler.

func (w *http2writeResHeaders) staysWithinBuffer(max int) bool
func (w *http2writeResHeaders) writeFrame(ctx http2writeContext) error
func (w *http2writeResHeaders) writeHeaderBlock(ctx http2writeContext, frag []byte, firstFrag, lastFrag bool) error
type http2writePushPromise struct {
	streamID uint32   // pusher stream
	method   string   // for :method
	url      *url.URL // for :scheme, :authority, :path
	h        Header

	// Creates an ID for a pushed stream. This runs on serveG just before
	// the frame is written. The returned ID is copied to promisedID.
	allocatePromisedID func() (uint32, error)
	promisedID         uint32
}

writePushPromise is a request to write a PUSH_PROMISE and 0+ CONTINUATION frames.

func (w *http2writePushPromise) staysWithinBuffer(max int) bool
func (w *http2writePushPromise) writeFrame(ctx http2writeContext) error
func (w *http2writePushPromise) writeHeaderBlock(ctx http2writeContext, frag []byte, firstFrag, lastFrag bool) error
type http2write100ContinueHeadersFrame struct {
	streamID uint32
}
func (w http2write100ContinueHeadersFrame) writeFrame(ctx http2writeContext) error
func (w http2write100ContinueHeadersFrame) staysWithinBuffer(max int) bool
type http2writeWindowUpdate struct {
	streamID uint32 // or 0 for conn-level
	n        uint32
}
func (wu http2writeWindowUpdate) staysWithinBuffer(max int) bool
func (wu http2writeWindowUpdate) writeFrame(ctx http2writeContext) error
type http2WriteScheduler interface {
	// 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.
	OpenStream(streamID uint32, options http2OpenStreamOptions)

	// 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.
	CloseStream(streamID uint32)

	// 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
	AdjustStream(streamID uint32, priority http2PriorityParam)

	// 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.
	Push(wr http2FrameWriteRequest)

	// 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. No frames should be discarded except by CloseStream.
	Pop() (wr http2FrameWriteRequest, ok bool)
}

WriteScheduler is the interface implemented by HTTP/2 write schedulers. Methods are never called concurrently.

func http2NewPriorityWriteScheduler(cfg *http2PriorityWriteSchedulerConfig) http2WriteScheduler

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.

func http2NewRandomWriteScheduler() http2WriteScheduler

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.

type http2OpenStreamOptions struct {
	// PusherID is zero if the stream was initiated by the client. Otherwise,
	// PusherID names the stream that pushed the newly opened stream.
	PusherID uint32
}

OpenStreamOptions specifies extra options for WriteScheduler.OpenStream.

type http2FrameWriteRequest struct {
	// 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.
	write http2writeFramer

	// stream is the stream on which this frame will be written.
	// nil for non-stream frames like PING and SETTINGS.
	stream *http2stream

	// 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.
	done chan error
}

FrameWriteRequest is a request to write a frame.

func (wr http2FrameWriteRequest) StreamID() uint32

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.

func (wr http2FrameWriteRequest) isControl() bool

isControl reports whether wr is a control frame for MaxQueuedControlFrames purposes. That includes non-stream frames and RST_STREAM frames.

func (wr http2FrameWriteRequest) DataSize() int

DataSize returns the number of flow control bytes that must be consumed to write this entire frame. This is 0 for non-DATA frames.

func (wr http2FrameWriteRequest) Consume(n int32) (http2FrameWriteRequest, http2FrameWriteRequest, int)

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.

func (wr http2FrameWriteRequest) String() string

String is for debugging only.

func (wr *http2FrameWriteRequest) replyToWriter(err error)

replyToWriter sends err to wr.done and panics if the send must block This does nothing if wr.done is nil.

type http2writeQueue struct {
	s []http2FrameWriteRequest
}

writeQueue is used by implementations of WriteScheduler.

func (q *http2writeQueue) empty() bool
func (q *http2writeQueue) push(wr http2FrameWriteRequest)
func (q *http2writeQueue) shift() http2FrameWriteRequest
func (q *http2writeQueue) consume(n int32) (http2FrameWriteRequest, bool)

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.

type http2writeQueuePool []*http2writeQueue
func (p *http2writeQueuePool) put(q *http2writeQueue)

put inserts an unused writeQueue into the pool.

func (p *http2writeQueuePool) get() *http2writeQueue

get returns an empty writeQueue.

type http2PriorityWriteSchedulerConfig struct {
	// 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."
	MaxClosedNodesInTree int

	// 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).
	MaxIdleNodesInTree int

	// 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.
	ThrottleOutOfOrderWrites bool
}

PriorityWriteSchedulerConfig configures a priorityWriteScheduler.

type http2priorityNodeState int
type http2priorityNode struct {
	q            http2writeQueue        // queue of pending frames to write
	id           uint32                 // id of the stream, or 0 for the root of the tree
	weight       uint8                  // the actual weight is weight+1, so the value is in [1,256]
	state        http2priorityNodeState // open | closed | idle
	bytes        int64                  // number of bytes written by this node, or 0 if closed
	subtreeBytes int64                  // sum(node.bytes) of all nodes in this subtree

	// These links form the priority tree.
	parent     *http2priorityNode
	kids       *http2priorityNode // start of the kids list
	prev, next *http2priorityNode // doubly-linked list of siblings
}

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.

func (n *http2priorityNode) setParent(parent *http2priorityNode)
func (n *http2priorityNode) addBytes(b int64)
func (n *http2priorityNode) walkReadyInOrder(openParent bool, tmp *[]*http2priorityNode, f func(*http2priorityNode, bool) bool) bool

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

type http2sortPriorityNodeSiblings []*http2priorityNode
func (z http2sortPriorityNodeSiblings) Len() int
func (z http2sortPriorityNodeSiblings) Swap(i, k int)
func (z http2sortPriorityNodeSiblings) Less(i, k int) bool
type http2priorityWriteScheduler struct {
	// root is the root of the priority tree, where root.id = 0.
	// The root queues control frames that are not associated with any stream.
	root http2priorityNode

	// nodes maps stream ids to priority tree nodes.
	nodes map[uint32]*http2priorityNode

	// maxID is the maximum stream id in nodes.
	maxID uint32

	// 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.
	closedNodes, idleNodes []*http2priorityNode

	// From the config.
	maxClosedNodesInTree int
	maxIdleNodesInTree   int
	writeThrottleLimit   int32
	enableWriteThrottle  bool

	// tmp is scratch space for priorityNode.walkReadyInOrder to reduce allocations.
	tmp []*http2priorityNode

	// pool of empty queues for reuse.
	queuePool http2writeQueuePool
}
func (ws *http2priorityWriteScheduler) OpenStream(streamID uint32, options http2OpenStreamOptions)
func (ws *http2priorityWriteScheduler) CloseStream(streamID uint32)
func (ws *http2priorityWriteScheduler) AdjustStream(streamID uint32, priority http2PriorityParam)
func (ws *http2priorityWriteScheduler) Push(wr http2FrameWriteRequest)
func (ws *http2priorityWriteScheduler) Pop() (wr http2FrameWriteRequest, ok bool)
func (ws *http2priorityWriteScheduler) addClosedOrIdleNode(list *[]*http2priorityNode, maxSize int, n *http2priorityNode)
func (ws *http2priorityWriteScheduler) removeNode(n *http2priorityNode)
type http2randomWriteScheduler struct {
	// zero are frames not associated with a specific stream.
	zero http2writeQueue

	// sq contains the stream-specific queues, keyed by stream ID.
	// When a stream is idle, closed, or emptied, it's deleted
	// from the map.
	sq map[uint32]*http2writeQueue

	// pool of empty queues for reuse.
	queuePool http2writeQueuePool
}
func (ws *http2randomWriteScheduler) OpenStream(streamID uint32, options http2OpenStreamOptions)
func (ws *http2randomWriteScheduler) CloseStream(streamID uint32)
func (ws *http2randomWriteScheduler) AdjustStream(streamID uint32, priority http2PriorityParam)
func (ws *http2randomWriteScheduler) Push(wr http2FrameWriteRequest)
func (ws *http2randomWriteScheduler) Pop() (http2FrameWriteRequest, bool)
type Header map[string][]string

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

The keys should be in canonical form, as returned by CanonicalHeaderKey.

func cloneOrMakeHeader(hdr Header) Header

cloneOrMakeHeader invokes Header.Clone but if the result is nil, it'll instead make and return a non-nil Header.

func http2cloneHeader(h Header) Header
func fixTrailer(header Header, chunked bool) (Header, error)

Parse the trailer header

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

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

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

Set sets the header entries associated with key to the single element value. It replaces any existing values associated with key. The key is case insensitive; it is canonicalized by textproto.CanonicalMIMEHeaderKey. To use non-canonical keys, assign to the map directly.

func (h Header) Get(key string) string

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. To use non-canonical keys, access the map directly.

func (h Header) Values(key string) []string

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.

func (h Header) get(key string) string

get is like Get, but key must already be in CanonicalHeaderKey form.

func (h Header) has(key string) bool

has reports whether h has the provided key defined, even if it's set to 0-length slice.

func (h Header) Del(key string)

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

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

Write writes a header in wire format.

func (h Header) write(w io.Writer, trace *httptrace.ClientTrace) error
func (h Header) Clone() Header

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

func (h Header) sortedKeyValues(exclude map[string]bool) (kvs []keyValues, hs *headerSorter)

sortedKeyValues returns h's keys sorted in the returned kvs slice. The headerSorter used to sort is also returned, for possible return to headerSorterCache.

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

WriteSubset writes a header in wire format. If exclude is not nil, keys where exclude[key] == true are not written. Keys are not canonicalized before checking the exclude map.

func (h Header) writeSubset(w io.Writer, exclude map[string]bool, trace *httptrace.ClientTrace) error
type stringWriter struct {
	w io.Writer
}

stringWriter implements WriteString on a Writer.

func (w stringWriter) WriteString(s string) (n int, err error)
type keyValues struct {
	key    string
	values []string
}
type headerSorter struct {
	kvs []keyValues
}

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.

func (s *headerSorter) Len() int
func (s *headerSorter) Swap(i, j int)
func (s *headerSorter) Less(i, j int) bool
type incomparable [0]func()

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

type contextKey struct {
	name string
}

contextKey is a value for use with context.WithValue. It's used as a pointer so it fits in an interface{} without allocation.

func (k *contextKey) String() string
type noBody struct{}
func (noBody) Read([]byte) (int, error)
func (noBody) Close() error
func (noBody) WriteTo(io.Writer) (int64, error)
type PushOptions struct {
	// Method specifies the HTTP method for the promised request.
	// If set, it must be "GET" or "HEAD". Empty means "GET".
	Method string

	// Header specifies additional promised request headers. This cannot
	// include HTTP/2 pseudo header fields like ":path" and ":scheme",
	// which will be added automatically.
	Header Header
}

PushOptions describes options for Pusher.Push.

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

type CookieJar interface {
	// SetCookies handles the receipt of the cookies in a reply for the
	// given URL.  It may or may not choose to save the cookies, depending
	// on the jar's policy and implementation.
	SetCookies(u *url.URL, cookies []*Cookie)

	// Cookies returns the cookies to send in a request for the given URL.
	// It is up to the implementation to honor the standard cookie use
	// restrictions such as in RFC 6265.
	Cookies(u *url.URL) []*Cookie
}

A CookieJar manages storage and use of cookies in HTTP requests.

Implementations of CookieJar must be safe for concurrent use by multiple goroutines.

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

type ProtocolError struct {
	ErrorString string
}

ProtocolError represents an HTTP protocol error.

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

func (pe *ProtocolError) Error() string
type Request struct {
	// 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.
	Method string

	// 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.
	URL *url.URL

	// The protocol version for incoming server requests.
	//
	// For client requests, these fields are ignored. The HTTP
	// client code always uses either HTTP/1.1 or HTTP/2.
	// See the docs on Transport for details.
	Proto      string // "HTTP/1.0"
	ProtoMajor int    // 1
	ProtoMinor int    // 0

	// Header contains the request header fields either received
	// by the server or to be sent by the client.
	//
	// If a server received a request with header lines,
	//
	//	Host: example.com
	//	accept-encoding: gzip, deflate
	//	Accept-Language: en-us
	//	fOO: Bar
	//	foo: two
	//
	// then
	//
	//	Header = map[string][]string{
	//		"Accept-Encoding": {"gzip, deflate"},
	//		"Accept-Language": {"en-us"},
	//		"Foo": {"Bar", "two"},
	//	}
	//
	// For incoming requests, the Host header is promoted to the
	// Request.Host field and removed from the Header map.
	//
	// HTTP defines that header names are case-insensitive. The
	// request parser implements this by using CanonicalHeaderKey,
	// making the first character and any characters following a
	// hyphen uppercase and the rest lowercase.
	//
	// For client requests, certain headers such as Content-Length
	// and Connection are automatically written when needed and
	// values in Header may be ignored. See the documentation
	// for the Request.Write method.
	Header Header

	// 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.
	Body io.ReadCloser

	// GetBody defines an optional func to return a new copy of
	// Body. It is used for client requests when a redirect requires
	// reading the body more than once. Use of GetBody still
	// requires setting Body.
	//
	// For server requests, it is unused.
	GetBody func() (io.ReadCloser, error)

	// ContentLength records the length of the associated content.
	// The value -1 indicates that the length is unknown.
	// Values >= 0 indicate that the given number of bytes may
	// be read from Body.
	//
	// For client requests, a value of 0 with a non-nil Body is
	// also treated as unknown.
	ContentLength int64

	// TransferEncoding lists the transfer encodings from outermost to
	// innermost. An empty list denotes the "identity" encoding.
	// TransferEncoding can usually be ignored; chunked encoding is
	// automatically added and removed as necessary when sending and
	// receiving requests.
	TransferEncoding []string

	// Close indicates whether to close the connection after
	// replying to this request (for servers) or after sending this
	// request and reading its response (for clients).
	//
	// For server requests, the HTTP server handles this automatically
	// and this field is not needed by Handlers.
	//
	// For client requests, setting this field prevents re-use of
	// TCP connections between requests to the same hosts, as if
	// Transport.DisableKeepAlives were set.
	Close bool

	// 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.
	Host string

	// 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.
	Form url.Values

	// PostForm contains the parsed form data from PATCH, POST
	// or PUT body parameters.
	//
	// This field is only available after ParseForm is called.
	// The HTTP client ignores PostForm and uses Body instead.
	PostForm url.Values

	// MultipartForm is the parsed multipart form, including file uploads.
	// This field is only available after ParseMultipartForm is called.
	// The HTTP client ignores MultipartForm and uses Body instead.
	MultipartForm *multipart.Form

	// Trailer specifies additional headers that are sent after the request
	// body.
	//
	// For server requests, the Trailer map initially contains only the
	// trailer keys, with nil values. (The client declares which trailers it
	// will later send.)  While the handler is reading from Body, it must
	// not reference Trailer. After reading from Body returns EOF, Trailer
	// can be read again and will contain non-nil values, if they were sent
	// by the client.
	//
	// For client requests, Trailer must be initialized to a map containing
	// the trailer keys to later send. The values may be nil or their final
	// values. The ContentLength must be 0 or -1, to send a chunked request.
	// After the HTTP request is sent the map values can be updated while
	// the request body is read. Once the body returns EOF, the caller must
	// not mutate Trailer.
	//
	// Few HTTP clients, servers, or proxies support HTTP trailers.
	Trailer Header

	// 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.
	RemoteAddr string

	// 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.
	RequestURI string

	// TLS allows HTTP servers and other software to record
	// information about the TLS connection on which the request
	// was received. This field is not filled in by ReadRequest.
	// The HTTP server in this package sets the field for
	// TLS-enabled connections before invoking a handler;
	// otherwise it leaves the field nil.
	// This field is ignored by the HTTP client.
	TLS *tls.ConnectionState

	// Cancel is an optional channel whose closure indicates that the client
	// request should be regarded as canceled. Not all implementations of
	// RoundTripper may support Cancel.
	//
	// For server requests, this field is not applicable.
	//
	// Deprecated: Set the Request's context with NewRequestWithContext
	// instead. If a Request's Cancel field and context are both
	// set, it is undefined whether Cancel is respected.
	Cancel <-chan struct{}

	// Response is the redirect response which caused this request
	// to be created. This field is only populated during client
	// redirects.
	Response *Response

	// ctx is either the client or server context. It should only
	// be modified via copying the whole Request using WithContext.
	// It is unexported to prevent people from using Context wrong
	// and mutating the contexts held by callers of the same request.
	ctx context.Context
}

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

The field semantics differ slightly between client and server usage. In addition to the notes on the fields below, see the documentation for Request.Write and RoundTripper.

func http2shouldRetryRequest(req *Request, err error, afterBodyWrite bool) (*Request, error)

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.

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

NewRequest wraps NewRequestWithContext using the background context.

func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error)

NewRequestWithContext returns a new Request given a method, URL, and optional body.

If the provided body is also an io.Closer, the returned Request.Body is set to body and will be closed by the Client methods Do, Post, and PostForm, and Transport.RoundTrip.

NewRequestWithContext returns a Request suitable for use with Client.Do or Transport.RoundTrip. To create a request for use with testing a Server Handler, either use the NewRequest function in the net/http/httptest package, use ReadRequest, or manually update the Request fields. For an outgoing client request, the context controls the entire lifetime of a request and its response: obtaining a connection, sending the request, and reading the response headers and body. See the Request type's documentation for the difference between inbound and outbound request fields.

If body is of type *bytes.Buffer, *bytes.Reader, or *strings.Reader, the returned request's ContentLength is set to its exact value (instead of -1), GetBody is populated (so 307 and 308 redirects can replay the body), and Body is set to NoBody if the ContentLength is 0.

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

ReadRequest reads and parses an incoming request from b.

ReadRequest is a low-level function and should only be used for specialized applications; most code should use the Server to read requests and handle them via the Handler interface. ReadRequest only supports HTTP/1.x requests. For HTTP/2, use golang.org/x/net/http2.

func readRequest(b *bufio.Reader, deleteHostHeader bool) (req *Request, err error)
func setupRewindBody(req *Request) *Request

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.

func rewindBody(req *Request) (rewound *Request, err error)

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

func dummyReq(method string) *Request
func dummyReq11(method string) *Request
func dummyRequest(method string) *Request
func dummyRequestWithBody(method string) *Request
func dummyRequestWithBodyNoGetBody(method string) *Request
func (r *Request) Context() context.Context

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

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

For outgoing client requests, the context controls 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.

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

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

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 change the context of a request, such as an incoming request you want to modify before sending back out, use Request.Clone. Between those two uses, it's rare to need WithContext.

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

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.

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

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

func (r *Request) UserAgent() string

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

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

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

func (r *Request) Cookie(name string) (*Cookie, error)

Cookie returns the named cookie provided in the request or ErrNoCookie if not found. If multiple cookies match the given name, only one cookie will be returned.

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

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

func (r *Request) Referer() string

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

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

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

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.

func (r *Request) multipartReader(allowMixed bool) (*multipart.Reader, error)
func (r *Request) isH2Upgrade() bool

isH2Upgrade reports whether r represents the http2 "client preface" magic string.

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

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

Host
URL
Method (defaults to "GET")
Header
ContentLength
TransferEncoding
Body

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

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

WriteProxy is like Write but writes the request in the form expected by an HTTP proxy. In particular, WriteProxy writes the initial Request-URI line of the request with an absolute URI, per section 5.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.

func (r *Request) write(w io.Writer, usingProxy bool, extraHeaders Header, waitForContinue func() bool) (err error)

extraHeaders may be nil waitForContinue may be nil always closes body

func (r *Request) BasicAuth() (username, password string, ok bool)

BasicAuth returns the username and password provided in the request's Authorization header, if the request uses HTTP Basic Authentication. See RFC 2617, Section 2.

func (r *Request) SetBasicAuth(username, password string)

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

With HTTP Basic Authentication the provided username and password are not encrypted.

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.

func (r *Request) ParseForm() error

ParseForm populates r.Form and r.PostForm.

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

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

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

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

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

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

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

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.

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

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

func (r *Request) expectsContinue() bool
func (r *Request) wantsHttp10KeepAlive() bool
func (r *Request) wantsClose() bool
func (r *Request) closeBody() error
func (r *Request) isReplayable() bool
func (r *Request) outgoingLength() int64

outgoingLength reports the Content-Length of this outgoing (Client) request. It maps 0 into -1 (unknown) when the Body is non-nil.

func (r *Request) requiresHTTP1() bool

requiresHTTP1 reports whether this request requires being sent on an HTTP/1 connection.

func (r *Request) WithT(t *testing.T) *Request
func (r *Request) ExportIsReplayable() bool
type requestBodyReadError struct{ error }

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.

type maxBytesReader struct {
	w   ResponseWriter
	r   io.ReadCloser // underlying reader
	n   int64         // max bytes remaining
	err error         // sticky error
}
func (l *maxBytesReader) Read(p []byte) (n int, err error)
func (l *maxBytesReader) Close() error
type requestTooLarger interface {
	requestTooLarge()
}

The server code and client code both use maxBytesReader. This "requestTooLarge" check is only used by the server code. To prevent binaries which only using the HTTP Client code (such as cmd/go) from also linking in the HTTP server, don't use a static type assertion to the server "*response" type. Check this interface instead:

type Response struct {
	Status     string // e.g. "200 OK"
	StatusCode int    // e.g. 200
	Proto      string // e.g. "HTTP/1.0"
	ProtoMajor int    // e.g. 1
	ProtoMinor int    // e.g. 0

	// Header maps header keys to values. If the response had multiple
	// headers with the same key, they may be concatenated, with comma
	// delimiters.  (RFC 7230, section 3.2.2 requires that multiple headers
	// be semantically equivalent to a comma-delimited sequence.) When
	// Header values are duplicated by other fields in this struct (e.g.,
	// ContentLength, TransferEncoding, Trailer), the field values are
	// authoritative.
	//
	// Keys in the map are canonicalized (see CanonicalHeaderKey).
	Header Header

	// 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.
	Body io.ReadCloser

	// ContentLength records the length of the associated content. The
	// value -1 indicates that the length is unknown. Unless Request.Method
	// is "HEAD", values >= 0 indicate that the given number of bytes may
	// be read from Body.
	ContentLength int64

	// Contains transfer encodings from outer-most to inner-most. Value is
	// nil, means that "identity" encoding is used.
	TransferEncoding []string

	// Close records whether the header directed that the connection be
	// closed after reading Body. The value is advice for clients: neither
	// ReadResponse nor Response.Write ever closes a connection.
	Close bool

	// 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.
	Uncompressed bool

	// 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.
	Trailer Header

	// Request is the request that was sent to obtain this Response.
	// Request's Body is nil (having already been consumed).
	// This is only populated for Client requests.
	Request *Request

	// TLS contains information about the TLS connection on which the
	// response was received. It is nil for unencrypted responses.
	// The pointer is shared between responses and should not be
	// modified.
	TLS *tls.ConnectionState
}

Response represents the response from an HTTP request.

The Client and Transport return Responses from servers once the response headers have been received. The response body is streamed on demand as the Body field is read.

func send(ireq *Request, rt RoundTripper, deadline time.Time) (resp *Response, didTimeout func() bool, err error)

send issues an HTTP request. Caller should close resp.Body when done reading from it.

func Get(url string) (resp *Response, err error)

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

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

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

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

Get is a wrapper around DefaultClient.Get.

To make a request with custom headers, use NewRequest and DefaultClient.Do.

func Post(url, contentType string, body io.Reader) (resp *Response, err error)

Post issues a POST to the specified URL.

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

If the provided body is an io.Closer, it is closed after the request.

Post is a wrapper around DefaultClient.Post.

To set custom headers, use NewRequest and DefaultClient.Do.

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

func PostForm(url string, data url.Values) (resp *Response, err error)

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

The Content-Type header is set to application/x-www-form-urlencoded. To set other headers, use NewRequest and DefaultClient.Do.

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

PostForm is a wrapper around DefaultClient.PostForm.

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

func Head(url string) (resp *Response, err error)

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

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

Head is a wrapper around DefaultClient.Head

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

ReadResponse reads and returns an HTTP response from r. The req parameter optionally specifies the Request that corresponds to this Response. If nil, a GET request is assumed. Clients must call resp.Body.Close when finished reading resp.Body. After that call, clients can inspect resp.Trailer to find key/value pairs included in the response trailer.

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

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

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

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

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

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

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

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

This method consults the following fields of the response r:

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.

func (r *Response) closeBody()
func (r *Response) bodyIsWritable() bool

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.

func (r *Response) isProtocolSwitch() bool

isProtocolSwitch reports whether the response code and header indicate a successful protocol upgrade response.

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

A Handler responds to an HTTP request.

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

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

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

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

func FileServer(root FileSystem) Handler

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)))

func NotFoundHandler() Handler

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

func StripPrefix(prefix string, h Handler) Handler

StripPrefix returns a handler that serves HTTP requests by removing the given prefix from the request URL's Path (and 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.

func RedirectHandler(url string, code int) Handler

RedirectHandler returns a request handler that redirects each request it receives to the given url using the given status code.

The provided code should be in the 3xx range and is usually StatusMovedPermanently, StatusFound or StatusSeeOther.

func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler

TimeoutHandler returns a Handler that runs h with the given time limit.

The new Handler calls h.ServeHTTP to handle each request, but if a call runs for longer than its time limit, the handler responds with a 503 Service Unavailable error and the given message in its body. (If msg is empty, a suitable default message will be sent.) After such a timeout, writes by h to its ResponseWriter will return ErrHandlerTimeout.

TimeoutHandler supports the Pusher interface but does not support the Hijacker or Flusher interfaces.

func NewTestTimeoutHandler(handler Handler, ch <-chan time.Time) Handler
type ResponseWriter interface {
	// 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 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.
	Header() Header

	// 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.
	Write([]byte) (int, error)

	// WriteHeader sends an HTTP response header with the provided
	// status code.
	//
	// If WriteHeader is not called explicitly, the first call to Write
	// will trigger an implicit WriteHeader(http.StatusOK).
	// Thus explicit calls to WriteHeader are mainly used to
	// send error codes.
	//
	// The provided code must be a valid HTTP 1xx-5xx status code.
	// Only one header may be written. Go does not currently
	// support sending user-defined 1xx informational headers,
	// with the exception of 100-continue response header that the
	// Server sends automatically when the Request.Body is read.
	WriteHeader(statusCode int)
}

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.

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

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

The default HTTP/1.x and HTTP/2 ResponseWriter implementations support Flusher, but ResponseWriter wrappers may not. Handlers should always test for this ability at runtime.

Note that even for ResponseWriters that support Flush, if the client is connected through an HTTP proxy, the buffered data may not reach the client until the response completes.

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

The Hijacker interface is implemented by ResponseWriters that 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.

type CloseNotifier interface {
	// CloseNotify returns a channel that receives at most a
	// single value (true) when the client connection has gone
	// away.
	//
	// CloseNotify may wait to notify until Request.Body has been
	// fully read.
	//
	// After the Handler has returned, there is no guarantee
	// that the channel receives a value.
	//
	// If the protocol is HTTP/1.1 and CloseNotify is called while
	// processing an idempotent request (such 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.
	CloseNotify() <-chan bool
}

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

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

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

type conn struct {
	// server is the server on which the connection arrived.
	// Immutable; never nil.
	server *Server

	// cancelCtx cancels the connection-level context.
	cancelCtx context.CancelFunc

	// 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.
	rwc net.Conn

	// 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.
	remoteAddr string

	// tlsState is the TLS connection state when using TLS.
	// nil means not TLS.
	tlsState *tls.ConnectionState

	// werr is set to the first write error to rwc.
	// It is set via checkConnErrorWriter{w}, where bufw writes.
	werr error

	// 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.
	r *connReader

	// bufr reads from r.
	bufr *bufio.Reader

	// bufw writes to checkConnErrorWriter{c}, which populates werr on error.
	bufw *bufio.Writer

	// lastMethod is the method of the most recent request
	// on this connection, if any.
	lastMethod string

	curReq atomic.Value // of *response (which has a Request in it)

	curState struct{ atomic uint64 } // packed (unixtime<<8|uint8(ConnState))

	// mu guards hijackedv
	mu sync.Mutex

	// hijackedv is whether this connection has been hijacked
	// by a Handler with the Hijacker interface.
	// It is guarded by mu.
	hijackedv bool
}

A conn represents the server side of an HTTP connection.

func (c *conn) hijacked() bool
func (c *conn) hijackLocked() (rwc net.Conn, buf *bufio.ReadWriter, err error)

c.mu must be held.

func (c *conn) readRequest(ctx context.Context) (w *response, err error)

Read next request from connection.

func (c *conn) finalFlush()
func (c *conn) close()

Close the connection.

func (c *conn) closeWriteAndWait()

closeWrite flushes any outstanding data and sends a FIN packet (if client is connected via TCP), signalling 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

func (c *conn) setState(nc net.Conn, state ConnState, runHook bool)
func (c *conn) getState() (state ConnState, unixSec int64)
func (c *conn) serve(ctx context.Context)

Serve a new connection.

type chunkWriter struct {
	res *response

	// 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.
	header Header

	// 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.
	wroteHeader bool

	// set by the writeHeader method:
	chunking bool // using chunked transfer encoding for reply body
}

chunkWriter writes to a response's conn buffer, and is the writer wrapped by the response.bufw 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.

func (cw *chunkWriter) Write(p []byte) (n int, err error)
func (cw *chunkWriter) flush()
func (cw *chunkWriter) close()
func (cw *chunkWriter) writeHeader(p []byte)

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.

type response struct {
	conn             *conn
	req              *Request // request for this response
	reqBody          io.ReadCloser
	cancelCtx        context.CancelFunc // when ServeHTTP exits
	wroteHeader      bool               // reply header has been (logically) written
	wroteContinue    bool               // 100 Continue response was written
	wants10KeepAlive bool               // HTTP/1.0 w/ Connection "keep-alive"
	wantsClose       bool               // HTTP request has Connection "close"

	// canWriteContinue is a boolean value accessed as an atomic int32
	// 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.
	canWriteContinue atomicBool
	writeContinueMu  sync.Mutex

	w  *bufio.Writer // buffers output in chunks to chunkWriter
	cw chunkWriter

	// 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.
	handlerHeader Header
	calledHeader  bool // handler accessed handlerHeader via Header

	written       int64 // number of bytes written in body
	contentLength int64 // explicitly-declared Content-Length; or -1
	status        int   // status code passed to WriteHeader

	// 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.
	closeAfterReply bool

	// 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.
	requestBodyLimitHit bool

	// 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.
	trailers []string

	handlerDone atomicBool // set true when the handler exits

	// Buffers for Date, Content-Length, and status code
	dateBuf   [len(TimeFormat)]byte
	clenBuf   [10]byte
	statusBuf [3]byte

	// 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?
	closeNotifyCh  chan bool
	didCloseNotify int32 // atomic (only 0->1 winner should send)
}

A response represents the server side of an HTTP response.

func (w *response) finalTrailers() Header

finalTrailers is called after the Handler exits and returns a non-nil value if the Handler set any trailers.

func (w *response) declareTrailer(k string)

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.

func (w *response) requestTooLarge()

requestTooLarge is called by maxBytesReader when too much input has been read from the client.

func (w *response) needsSniff() bool

needsSniff reports whether a Content-Type still needs to be sniffed.

func (w *response) ReadFrom(src io.Reader) (n int64, err error)

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.

func (w *response) Header() Header
func (w *response) WriteHeader(code int)
func (w *response) bodyAllowed() bool

bodyAllowed reports whether a Write is allowed for this response type. It's illegal to call this before the header has been flushed.

func (w *response) Write(data []byte) (n int, err 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.

  1. conn.buf, 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:

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

func (w *response) WriteString(data string) (n int, err error)
func (w *response) write(lenData int, dataB []byte, dataS string) (n int, err error)

either dataB or dataS is non-zero.

func (w *response) finishRequest()
func (w *response) shouldReuseConnection() bool

shouldReuseConnection reports whether the underlying TCP connection can be reused. It must only be called after the handler is done executing.

func (w *response) closedRequestBodyEarly() bool
func (w *response) Flush()
func (w *response) sendExpectationFailed()
func (w *response) Hijack() (rwc net.Conn, buf *bufio.ReadWriter, err error)

Hijack implements the Hijacker.Hijack method. Our response is both a ResponseWriter and a Hijacker.

func (w *response) CloseNotify() <-chan bool
type atomicBool int32
func (b *atomicBool) isSet() bool
func (b *atomicBool) setTrue()
func (b *atomicBool) setFalse()
type writerOnly struct {
	io.Writer
}

writerOnly hides an io.Writer value's optional ReadFrom method from io.Copy.

type readResult struct {
	_   incomparable
	n   int
	err error
	b   byte // byte read, if n == 1
}
type connReader struct {
	conn *conn

	mu      sync.Mutex // guards following
	hasByte bool
	byteBuf [1]byte
	cond    *sync.Cond
	inRead  bool
	aborted bool  // set true before conn.rwc deadline is set to past
	remain  int64 // bytes remaining
}

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.

func (cr *connReader) lock()
func (cr *connReader) unlock()
func (cr *connReader) startBackgroundRead()
func (cr *connReader) backgroundRead()
func (cr *connReader) abortPendingRead()
func (cr *connReader) setReadLimit(remain int64)
func (cr *connReader) setInfiniteReadLimit()
func (cr *connReader) hitReadLimit() bool
func (cr *connReader) handleReadError(_ error)

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.

func (cr *connReader) closeNotify()

may be called from multiple goroutines.

func (cr *connReader) Read(p []byte) (n int, err error)
type expectContinueReader struct {
	resp       *response
	readCloser io.ReadCloser
	closed     atomicBool
	sawEOF     atomicBool
}

wrapper around io.ReadCloser which on first read, sends an HTTP/1.1 100 Continue header

func (ecr *expectContinueReader) Read(p []byte) (n int, err error)
func (ecr *expectContinueReader) Close() error
type extraHeader struct {
	contentType      string
	connection       string
	transferEncoding string
	date             []byte // written if not nil
	contentLength    []byte // written if not nil
}

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.

func (h extraHeader) Write(w *bufio.Writer)

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.

type closeWriter interface {
	CloseWrite() error
}
type statusError struct {
	code int
	text string
}

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.

func (e statusError) Error() string
type HandlerFunc func(ResponseWriter, *Request)

The HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers. If f is a function with the appropriate signature, HandlerFunc(f) is a Handler that calls f.

func http2new400Handler(err error) HandlerFunc
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request)

ServeHTTP calls f(w, r).

type redirectHandler struct {
	url  string
	code int
}

Redirect to a fixed URL

func (rh *redirectHandler) ServeHTTP(w ResponseWriter, r *Request)
type ServeMux struct {
	mu    sync.RWMutex
	m     map[string]muxEntry
	es    []muxEntry // slice of entries sorted from longest to shortest.
	hosts bool       // whether any patterns contain hostnames
}

ServeMux is an HTTP request multiplexer. It matches the URL of each incoming request against a list of registered patterns and calls the handler for the pattern that most closely matches the URL.

Patterns name fixed, rooted paths, like "/favicon.ico", or rooted subtrees, like "/images/" (note the trailing slash). Longer patterns take precedence over shorter ones, so that if there are handlers registered for both "/images/" and "/images/thumbnails/", the latter handler will be called for paths beginning "/images/thumbnails/" and the former will receive requests for any other paths in the "/images/" subtree.

Note that since a pattern ending in a slash names a rooted subtree, the pattern "/" matches all paths not matched by other registered patterns, not just the URL with Path == "/".

If a subtree has been registered and a request is received naming the subtree root without its trailing slash, ServeMux redirects that request to the subtree root (adding the trailing slash). This behavior can be overridden with a separate registration for the path without the trailing slash. For example, registering "/images/" causes ServeMux to redirect a request for "/images" to "/images/", unless "/images" has been registered separately.

Patterns may optionally begin with a host name, restricting matches to URLs on that host only. Host-specific patterns take precedence over general patterns, so that a handler might register for the two patterns "/codesearch" and "codesearch.google.com/" without also taking over requests for "http://www.google.com/".

ServeMux also takes care of sanitizing the URL request path and the Host header, stripping the port number and redirecting any request containing . or .. elements or repeated slashes to an equivalent, cleaner URL.

func NewServeMux() *ServeMux

NewServeMux allocates and returns a new ServeMux.

func (mux *ServeMux) match(path string) (h Handler, pattern string)

Find a handler on a handler map given a path string. Most-specific (longest) pattern wins.

func (mux *ServeMux) redirectToPathSlash(host, path string, u *url.URL) (*url.URL, bool)

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.

func (mux *ServeMux) shouldRedirectRLocked(host, path string) bool

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.

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

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

The path and host are used unchanged for CONNECT requests.

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

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

func (mux *ServeMux) handler(host, path string) (h Handler, pattern string)

handler is the main implementation of Handler. The path is known to be in canonical form, except for CONNECT methods.

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

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

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

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

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

HandleFunc registers the handler function for the given pattern.

type muxEntry struct {
	h       Handler
	pattern string
}
type Server struct {
	// Addr optionally specifies the TCP address for the server to listen on,
	// in the form "host:port". If empty, ":http" (port 80) is used.
	// The service names are defined in RFC 6335 and assigned by IANA.
	// See net.Dial for details of the address format.
	Addr string

	Handler Handler // handler to invoke, http.DefaultServeMux if nil

	// TLSConfig optionally provides a TLS configuration for use
	// by ServeTLS and ListenAndServeTLS. Note that this value is
	// cloned by ServeTLS and ListenAndServeTLS, so it's not
	// possible to modify the configuration with methods like
	// tls.Config.SetSessionTicketKeys. To use
	// SetSessionTicketKeys, use Server.Serve with a TLS Listener
	// instead.
	TLSConfig *tls.Config

	// ReadTimeout is the maximum duration for reading the entire
	// request, including the body.
	//
	// 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.
	ReadTimeout time.Duration

	// ReadHeaderTimeout is the amount of time allowed to read
	// request headers. The connection's read deadline is reset
	// after reading the headers and the Handler can decide what
	// is considered too slow for the body. If ReadHeaderTimeout
	// is zero, the value of ReadTimeout is used. If both are
	// zero, there is no timeout.
	ReadHeaderTimeout time.Duration

	// WriteTimeout is the maximum duration before timing out
	// writes of the response. It is reset whenever a new
	// request's header is read. Like ReadTimeout, it does not
	// let Handlers make decisions on a per-request basis.
	WriteTimeout time.Duration

	// 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.
	IdleTimeout time.Duration

	// MaxHeaderBytes controls the maximum number of bytes the
	// server will read parsing the request header's keys and
	// values, including the request line. It does not limit the
	// size of the request body.
	// If zero, DefaultMaxHeaderBytes is used.
	MaxHeaderBytes int

	// TLSNextProto optionally specifies a function to take over
	// ownership of the provided TLS connection when an ALPN
	// protocol upgrade has occurred. The map key is the protocol
	// name negotiated. The Handler argument should be used to
	// handle HTTP requests and will initialize the Request's TLS
	// and RemoteAddr if not already set. The connection is
	// automatically closed when the function returns.
	// If TLSNextProto is not nil, HTTP/2 support is not enabled
	// automatically.
	TLSNextProto map[string]func(*Server, *tls.Conn, Handler)

	// ConnState specifies an optional callback function that is
	// called when a client connection changes state. See the
	// ConnState type and associated constants for details.
	ConnState func(net.Conn, ConnState)

	// ErrorLog specifies an optional logger for errors accepting
	// connections, unexpected behavior from handlers, and
	// underlying FileSystem errors.
	// If nil, logging is done via the log package's standard logger.
	ErrorLog *log.Logger

	// BaseContext optionally specifies a function that returns
	// the base context for incoming requests on this server.
	// The provided Listener is the specific Listener that's
	// about to start accepting requests.
	// If BaseContext is nil, the default is context.Background().
	// If non-nil, it must return a non-nil context.
	BaseContext func(net.Listener) context.Context

	// ConnContext optionally specifies a function that modifies
	// the context used for a new connection c. The provided ctx
	// is derived from the base context and has a ServerContextKey
	// value.
	ConnContext func(ctx context.Context, c net.Conn) context.Context

	inShutdown atomicBool // true when when server is in shutdown

	disableKeepAlives int32     // accessed atomically.
	nextProtoOnce     sync.Once // guards setupHTTP2_* init
	nextProtoErr      error     // result of http2.ConfigureServer if used

	mu         sync.Mutex
	listeners  map[*net.Listener]struct{}
	activeConn map[*conn]struct{}
	doneChan   chan struct{}
	onShutdown []func()
}

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

func (srv *Server) newConn(rwc net.Conn) *conn

Create new connection from rwc.

func (srv *Server) maxHeaderBytes() int
func (srv *Server) initialReadLimitSize() int64
func (s *Server) getDoneChan() <-chan struct{}
func (s *Server) getDoneChanLocked() chan struct{}
func (s *Server) closeDoneChanLocked()
func (srv *Server) Close() error

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

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

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

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

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

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

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

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

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

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

func (s *Server) numListeners() int
func (s *Server) closeIdleConns() bool

closeIdleConns closes all idle connections and reports whether the server is quiescent.

func (s *Server) closeListenersLocked() error
func (srv *Server) ListenAndServe() error

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

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

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

func (srv *Server) shouldConfigureHTTP2ForServe() bool

shouldDoServeHTTP2 reports whether Server.Serve should configure automatic HTTP/2. (which sets up the srv.TLSNextProto map)

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

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

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.

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

ServeTLS accepts incoming connections on the Listener l, creating a new service goroutine for each. The service goroutines 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.

func (s *Server) trackListener(ln *net.Listener, add bool) 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).

func (s *Server) trackConn(c *conn, add bool)
func (s *Server) idleTimeout() time.Duration
func (s *Server) readHeaderTimeout() time.Duration
func (s *Server) doKeepAlives() bool
func (s *Server) shuttingDown() bool
func (srv *Server) SetKeepAlivesEnabled(v bool)

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

func (s *Server) logf(format string, args ...interface{})
func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error

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.

func (srv *Server) setupHTTP2_ServeTLS() error

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.

func (srv *Server) setupHTTP2_Serve() error

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.

func (srv *Server) onceSetNextProtoDefaults_Serve()
func (srv *Server) onceSetNextProtoDefaults()

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_*).

func (s *Server) ExportAllConnsIdle() bool
func (s *Server) ExportAllConnsByState() map[ConnState]int
type ConnState int

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

func (c ConnState) String() string
type serverHandler struct {
	srv *Server
}

serverHandler delegates to either the server's Handler or DefaultServeMux and also handles "OPTIONS *" requests.

func (sh serverHandler) ServeHTTP(rw ResponseWriter, req *Request)
type timeoutHandler struct {
	handler Handler
	body    string
	dt      time.Duration

	// When set, no context will be created and this context will
	// be used instead.
	testContext context.Context
}
func (h *timeoutHandler) errorBody() string
func (h *timeoutHandler) ServeHTTP(w ResponseWriter, r *Request)
type timeoutWriter struct {
	w    ResponseWriter
	h    Header
	wbuf bytes.Buffer
	req  *Request

	mu          sync.Mutex
	timedOut    bool
	wroteHeader bool
	code        int
}
func (tw *timeoutWriter) Push(target string, opts *PushOptions) error

Push implements the Pusher interface.

func (tw *timeoutWriter) Header() Header
func (tw *timeoutWriter) Write(p []byte) (int, error)
func (tw *timeoutWriter) writeHeaderLocked(code int)
func (tw *timeoutWriter) WriteHeader(code int)
type onceCloseListener struct {
	net.Listener
	once     sync.Once
	closeErr error
}

onceCloseListener wraps a net.Listener, protecting it from multiple Close calls.

func (oc *onceCloseListener) Close() error
func (oc *onceCloseListener) close()
type globalOptionsHandler struct{}

globalOptionsHandler responds to "OPTIONS *" requests.

func (globalOptionsHandler) ServeHTTP(w ResponseWriter, r *Request)
type initALPNRequest struct {
	ctx context.Context
	c   *tls.Conn
	h   serverHandler
}

initALPNRequest is an HTTP handler that initializes certain uninitialized fields in its *Request. Such partially-initialized Requests come from ALPN protocol handlers.

func (h initALPNRequest) BaseContext() context.Context

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.

func (h initALPNRequest) ServeHTTP(rw ResponseWriter, req *Request)
type loggingConn struct {
	name string
	net.Conn
}

loggingConn is used for debugging.

func (c *loggingConn) Write(p []byte) (n int, err error)
func (c *loggingConn) Read(p []byte) (n int, err error)
func (c *loggingConn) Close() (err error)
type checkConnErrorWriter struct {
	c *conn
}

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.

func (w checkConnErrorWriter) Write(p []byte) (n int, err error)
type sniffSig interface {
	// match returns the MIME type of the data, or "" if unknown.
	match(data []byte, firstNonWS int) string
}
type exactSig struct {
	sig []byte
	ct  string
}
func (e *exactSig) match(data []byte, firstNonWS int) string
type maskedSig struct {
	mask, pat []byte
	skipWS    bool
	ct        string
}
func (m *maskedSig) match(data []byte, firstNonWS int) string
type htmlSig []byte
func (h htmlSig) match(data []byte, firstNonWS int) string
type mp4Sig struct{}
func (mp4Sig) match(data []byte, firstNonWS int) string
type textSig struct{}
func (textSig) match(data []byte, firstNonWS int) string
type socksCommand int

A Command represents a SOCKS command.

func (cmd socksCommand) String() string
type socksAuthMethod int

An AuthMethod represents a SOCKS authentication method.

type socksReply int

A Reply represents a SOCKS command reply code.

func (code socksReply) String() string
type socksAddr struct {
	Name string // fully-qualified domain name
	IP   net.IP
	Port int
}

An Addr represents a SOCKS-specific address. Either Name or IP is used exclusively.

func (a *socksAddr) Network() string
func (a *socksAddr) String() string
type socksConn struct {
	net.Conn

	boundAddr net.Addr
}

A Conn represents a forward proxy connection.

func (c *socksConn) BoundAddr() net.Addr

BoundAddr returns the address assigned by the proxy server for connecting to the command target address from the proxy server.

type socksDialer struct {
	cmd          socksCommand // either CmdConnect or cmdBind
	proxyNetwork string       // network between a proxy server and a client
	proxyAddress string       // proxy server address

	// ProxyDial specifies the optional dial function for
	// establishing the transport connection.
	ProxyDial func(context.Context, string, string) (net.Conn, error)

	// AuthMethods specifies the list of request authentication
	// methods.
	// If empty, SOCKS client requests only AuthMethodNotRequired.
	AuthMethods []socksAuthMethod

	// 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.
	Authenticate func(context.Context, io.ReadWriter, socksAuthMethod) error
}

A Dialer holds SOCKS-specific options.

func socksNewDialer(network, address string) *socksDialer

NewDialer returns a new Dialer that dials through the provided proxy server's network and address.

func (d *socksDialer) connect(ctx context.Context, c net.Conn, address string) (_ net.Addr, ctxErr error)
func (d *socksDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error)

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.

func (d *socksDialer) DialWithConn(ctx context.Context, c net.Conn, network, address string) (net.Addr, error)

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.

func (d *socksDialer) Dial(network, address string) (net.Conn, error)

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.

func (d *socksDialer) validateTarget(network, address string) error
func (d *socksDialer) pathAddrs(address string) (proxy, dst net.Addr, err error)
type socksUsernamePassword struct {
	Username string
	Password string
}

UsernamePassword are the credentials for the username/password authentication method.

func (up *socksUsernamePassword) Authenticate(ctx context.Context, rw io.ReadWriter, auth socksAuthMethod) error

Authenticate authenticates a pair of username and password with the proxy server.

type errorReader struct {
	err error
}
func (r errorReader) Read(p []byte) (n int, err error)
type byteReader struct {
	b    byte
	done bool
}
func (br *byteReader) Read(p []byte) (n int, err error)
type transferWriter struct {
	Method           string
	Body             io.Reader
	BodyCloser       io.Closer
	ResponseToHEAD   bool
	ContentLength    int64 // -1 means unknown, 0 means exactly none
	Close            bool
	TransferEncoding []string
	Header           Header
	Trailer          Header
	IsResponse       bool
	bodyReadError    error // any non-EOF error from reading Body

	FlushHeaders bool            // flush headers to network before body
	ByteReadCh   chan readResult // non-nil if probeRequestBody called
}

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.

func newTransferWriter(r interface{}) (t *transferWriter, err error)
func (t *transferWriter) shouldSendChunkedRequestBody() bool

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.

func (t *transferWriter) probeRequestBody()

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.

func (t *transferWriter) shouldSendContentLength() bool
func (t *transferWriter) writeHeader(w io.Writer, trace *httptrace.ClientTrace) error
func (t *transferWriter) writeBody(w io.Writer) (err error)

always closes t.BodyCloser

func (t *transferWriter) doBodyCopy(dst io.Writer, src io.Reader) (n int64, err error)

doBodyCopy wraps a copy operation, with any resulting error also being saved in bodyReadError.

This function is only intended for use in writeBody.

func (t *transferWriter) unwrapBody() io.Reader

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

type transferReader struct {
	// Input
	Header        Header
	StatusCode    int
	RequestMethod string
	ProtoMajor    int
	ProtoMinor    int
	// Output
	Body          io.ReadCloser
	ContentLength int64
	Chunked       bool
	Close         bool
	Trailer       Header
}
func (t *transferReader) protoAtLeast(m, n int) bool
func (t *transferReader) parseTransferEncoding() error

parseTransferEncoding sets t.Chunked based on the Transfer-Encoding header.

type unsupportedTEError struct {
	err string
}

unsupportedTEError reports unsupported transfer-encodings.

func (uste *unsupportedTEError) Error() string
type body struct {
	src          io.Reader
	hdr          interface{}   // non-nil (Response or Request) value means read trailer
	r            *bufio.Reader // underlying wire-format reader for the trailer
	closing      bool          // is the connection to be closed after reading body?
	doEarlyClose bool          // whether Close should stop early

	mu         sync.Mutex // guards following, and calls to Read and Close
	sawEOF     bool
	closed     bool
	earlyClose bool   // Close called and we didn't read to the end of src
	onHitEOF   func() // if non-nil, func to call when EOF is Read
}

body turns a Reader into a ReadCloser. Close ensures that the body has been fully read and then reads the trailer if necessary.

func (b *body) Read(p []byte) (n int, err error)
func (b *body) readLocked(p []byte) (n int, err error)

Must hold b.mu.

func (b *body) readTrailer() error
func (b *body) unreadDataSizeLocked() int64

unreadDataSizeLocked returns the number of bytes of unread input. It returns -1 if unknown. b.mu must be held.

func (b *body) Close() error
func (b *body) didEarlyClose() bool
func (b *body) bodyRemains() bool

bodyRemains reports whether future Read calls might yield data.

func (b *body) registerOnHitEOF(fn func())
type bodyLocked struct {
	b *body
}

bodyLocked is a io.Reader reading from a *body when its mutex is already held.

func (bl bodyLocked) Read(p []byte) (n int, err error)
type finishAsyncByteRead struct {
	tw *transferWriter
}

finishAsyncByteRead finishes reading the 1-byte sniff from the ContentLength==0, Body!=nil case.

func (fr finishAsyncByteRead) Read(p []byte) (n int, err error)
type bufioFlushWriter struct{ w io.Writer }

bufioFlushWriter is an io.Writer wrapper that flushes all writes on its wrapped writer if it's a *bufio.Writer.

func (fw bufioFlushWriter) Write(p []byte) (n int, err error)
type Transport struct {
	idleMu       sync.Mutex
	closeIdle    bool                                // user has requested to close all idle conns
	idleConn     map[connectMethodKey][]*persistConn // most recently used at end
	idleConnWait map[connectMethodKey]wantConnQueue  // waiting getConns
	idleLRU      connLRU

	reqMu       sync.Mutex
	reqCanceler map[cancelKey]func(error)

	altMu    sync.Mutex   // guards changing altProto only
	altProto atomic.Value // of nil or map[string]RoundTripper, key is URI scheme

	connsPerHostMu   sync.Mutex
	connsPerHost     map[connectMethodKey]int
	connsPerHostWait map[connectMethodKey]wantConnQueue // waiting getConns

	// 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.
	Proxy func(*Request) (*url.URL, error)

	// DialContext specifies the dial function for creating unencrypted TCP connections.
	// If DialContext is nil (and the deprecated Dial below is also nil),
	// then the transport dials using package net.
	//
	// DialContext runs concurrently with calls to RoundTrip.
	// A RoundTrip call that initiates a dial may end up using
	// a connection dialed previously when the earlier connection
	// becomes idle before the later DialContext completes.
	DialContext func(ctx context.Context, network, addr string) (net.Conn, error)

	// Dial specifies the dial function for creating unencrypted TCP connections.
	//
	// Dial runs concurrently with calls to RoundTrip.
	// A RoundTrip call that initiates a dial may end up using
	// a connection dialed previously when the earlier connection
	// becomes idle before the later Dial completes.
	//
	// Deprecated: Use DialContext instead, which allows the transport
	// to cancel dials as soon as they are no longer needed.
	// If both are set, DialContext takes priority.
	Dial func(network, addr string) (net.Conn, error)

	// DialTLSContext specifies an optional dial function for creating
	// TLS connections for non-proxied HTTPS requests.
	//
	// If DialTLSContext is nil (and the deprecated DialTLS below is also nil),
	// DialContext and TLSClientConfig are used.
	//
	// If DialTLSContext is set, the Dial and DialContext hooks are not used for HTTPS
	// requests and the TLSClientConfig and TLSHandshakeTimeout
	// are ignored. The returned net.Conn is assumed to already be
	// past the TLS handshake.
	DialTLSContext func(ctx context.Context, network, addr string) (net.Conn, error)

	// DialTLS specifies an optional dial function for creating
	// TLS connections for non-proxied HTTPS requests.
	//
	// Deprecated: Use DialTLSContext instead, which allows the transport
	// to cancel dials as soon as they are no longer needed.
	// If both are set, DialTLSContext takes priority.
	DialTLS func(network, addr string) (net.Conn, error)

	// TLSClientConfig specifies the TLS configuration to use with
	// tls.Client.
	// If nil, the default configuration is used.
	// If non-nil, HTTP/2 support may not be enabled by default.
	TLSClientConfig *tls.Config

	// TLSHandshakeTimeout specifies the maximum amount of time waiting to
	// wait for a TLS handshake. Zero means no timeout.
	TLSHandshakeTimeout time.Duration

	// DisableKeepAlives, if true, disables HTTP keep-alives and
	// will only use the connection to the server for a single
	// HTTP request.
	//
	// This is unrelated to the similarly named TCP keep-alives.
	DisableKeepAlives bool

	// 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.
	DisableCompression bool

	// MaxIdleConns controls the maximum number of idle (keep-alive)
	// connections across all hosts. Zero means no limit.
	MaxIdleConns int

	// MaxIdleConnsPerHost, if non-zero, controls the maximum idle
	// (keep-alive) connections to keep per-host. If zero,
	// DefaultMaxIdleConnsPerHost is used.
	MaxIdleConnsPerHost int

	// 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.
	MaxConnsPerHost int

	// IdleConnTimeout is the maximum amount of time an idle
	// (keep-alive) connection will remain idle before closing
	// itself.
	// Zero means no limit.
	IdleConnTimeout time.Duration

	// ResponseHeaderTimeout, if non-zero, specifies the amount of
	// time to wait for a server's response headers after fully
	// writing the request (including its body, if any). This
	// time does not include the time to read the response body.
	ResponseHeaderTimeout time.Duration

	// ExpectContinueTimeout, if non-zero, specifies the amount of
	// time to wait for a server's first response headers after fully
	// writing the request headers if the request has an
	// "Expect: 100-continue" header. Zero means no timeout and
	// causes the body to be sent immediately, without
	// waiting for the server to approve.
	// This time does not include the time to send the request header.
	ExpectContinueTimeout time.Duration

	// 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.
	TLSNextProto map[string]func(authority string, c *tls.Conn) RoundTripper

	// ProxyConnectHeader optionally specifies headers to send to
	// proxies during CONNECT requests.
	// To set the header dynamically, see GetProxyConnectHeader.
	ProxyConnectHeader Header

	// GetProxyConnectHeader optionally specifies a func to return
	// headers to send to proxyURL during a CONNECT request to the
	// ip:port target.
	// If it returns an error, the Transport's RoundTrip fails with
	// that error. It can return (nil, nil) to not add headers.
	// If GetProxyConnectHeader is non-nil, ProxyConnectHeader is
	// ignored.
	GetProxyConnectHeader func(ctx context.Context, proxyURL *url.URL, target string) (Header, error)

	// MaxResponseHeaderBytes specifies a limit on how many
	// response bytes are allowed in the server's response
	// header.
	//
	// Zero means to use a default limit.
	MaxResponseHeaderBytes int64

	// WriteBufferSize specifies the size of the write buffer used
	// when writing to the transport.
	// If zero, a default (currently 4KB) is used.
	WriteBufferSize int

	// ReadBufferSize specifies the size of the read buffer used
	// when reading from the transport.
	// If zero, a default (currently 4KB) is used.
	ReadBufferSize int

	// nextProtoOnce guards initialization of TLSNextProto and
	// h2transport (via onceSetNextProtoDefaults)
	nextProtoOnce      sync.Once
	h2transport        h2Transport // non-nil if http2 wired up
	tlsNextProtoWasNil bool        // whether TLSNextProto was nil when the Once fired

	// 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.
	ForceAttemptHTTP2 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 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.

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

RoundTrip implements the RoundTripper interface.

For higher-level HTTP client support (such as handling of cookies and redirects), see Get, Post, and the Client type.

Like the RoundTripper interface, the error types returned by RoundTrip are unspecified.

func (t *Transport) writeBufferSize() int
func (t *Transport) readBufferSize() int
func (t *Transport) Clone() *Transport

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

func (t *Transport) hasCustomTLSDialer() bool
func (t *Transport) onceSetNextProtoDefaults()

onceSetNextProtoDefaults initializes TLSNextProto. It must be called via t.nextProtoOnce.Do.

func (t *Transport) useRegisteredProtocol(req *Request) bool

useRegisteredProtocol reports whether an alternate protocol (as registered with Transport.RegisterProtocol) should be respected for this request.

func (t *Transport) alternateRoundTripper(req *Request) RoundTripper

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.

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

roundTrip implements a RoundTripper over HTTP.

func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper)

RegisterProtocol registers a new protocol with scheme. The Transport will pass requests using the given scheme to rt. It is rt's responsibility to simulate HTTP request semantics.

RegisterProtocol can be used by other packages to provide implementations of protocol schemes like "ftp" or "file".

If rt.RoundTrip returns ErrSkipAltProtocol, the Transport will handle the RoundTrip itself for that one request, as if the protocol were not registered.

func (t *Transport) CloseIdleConnections()

CloseIdleConnections closes any connections which were previously connected from previous requests but are now sitting idle in a "keep-alive" state. It does not interrupt any connections currently in use.

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

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

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

func (t *Transport) cancelRequest(key cancelKey, err error) bool

Cancel an in-flight request, recording the error value. Returns whether the request was canceled.

func (t *Transport) connectMethodForRequest(treq *transportRequest) (cm connectMethod, err error)
func (t *Transport) putOrCloseIdleConn(pconn *persistConn)
func (t *Transport) maxIdleConnsPerHost() int
func (t *Transport) tryPutIdleConn(pconn *persistConn) 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.

func (t *Transport) queueForIdleConn(w *wantConn) (delivered bool)

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.

func (t *Transport) removeIdleConn(pconn *persistConn) bool

removeIdleConn marks pconn as dead.

func (t *Transport) removeIdleConnLocked(pconn *persistConn) bool

t.idleMu must be held.

func (t *Transport) setReqCanceler(key cancelKey, fn func(error))
func (t *Transport) replaceReqCanceler(key cancelKey, fn func(error)) bool

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.

func (t *Transport) dial(ctx context.Context, network, addr string) (net.Conn, error)
func (t *Transport) customDialTLS(ctx context.Context, network, addr string) (conn net.Conn, err error)
func (t *Transport) getConn(treq *transportRequest, cm connectMethod) (pc *persistConn, err error)

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.

func (t *Transport) queueForDial(w *wantConn)

queueForDial queues w to wait for permission to begin dialing. Once w receives permission to dial, it will do so in a separate goroutine.

func (t *Transport) dialConnFor(w *wantConn)

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 cancelled or unsuccessful, dialConnFor decrements t.connCount[w.cm.key()].

func (t *Transport) decConnsPerHost(key connectMethodKey)

decConnsPerHost decrements the per-host connection count for key, which may in turn give a different waiting goroutine permission to dial.

func (t *Transport) dialConn(ctx context.Context, cm connectMethod) (pconn *persistConn, err error)
func (t *Transport) NumPendingRequestsForTesting() int
func (t *Transport) IdleConnKeysForTesting() (keys []string)
func (t *Transport) IdleConnKeyCountForTesting() int
func (t *Transport) IdleConnStrsForTesting() []string
func (t *Transport) IdleConnStrsForTesting_h2() []string
func (t *Transport) IdleConnCountForTesting(scheme, addr string) int
func (t *Transport) IdleConnWaitMapSizeForTesting() int
func (t *Transport) IsIdleForTesting() bool
func (t *Transport) QueueForIdleConnForTesting()
func (t *Transport) PutIdleTestConn(scheme, addr string) bool

PutIdleTestConn reports whether it was able to insert a fresh persistConn for scheme, addr into the idle connection pool.

func (t *Transport) PutIdleTestConnH2(scheme, addr string, alt RoundTripper) bool

PutIdleTestConnH2 reports whether it was able to insert a fresh HTTP/2 persistConn for scheme, addr into the idle connection pool.

type cancelKey struct {
	req *Request
}

A cancelKey is the key of the reqCanceler map. We wrap the *Request in this type since we want to use the original request, not any transient one created by roundTrip.

type h2Transport interface {
	CloseIdleConnections()
}

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.

type transportRequest struct {
	*Request                         // original request, not to be mutated
	extra     Header                 // extra headers to write, or nil
	trace     *httptrace.ClientTrace // optional
	cancelKey cancelKey

	mu  sync.Mutex // guards err
	err error      // first setError value for mapRoundTripError to consider
}

transportRequest is a wrapper around a *Request that adds optional extra headers to write and stores any error to return from roundTrip.

func (tr *transportRequest) extraHeaders() Header
func (tr *transportRequest) setError(err error)
func (tr *transportRequest) logf(format string, args ...interface{})
type readTrackingBody struct {
	io.ReadCloser
	didRead  bool
	didClose bool
}
func (r *readTrackingBody) Read(data []byte) (int, error)
func (r *readTrackingBody) Close() error
type transportReadFromServerError struct {
	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.

func (e transportReadFromServerError) Unwrap() error
func (e transportReadFromServerError) Error() string
type wantConn struct {
	cm    connectMethod
	key   connectMethodKey // cm.key()
	ctx   context.Context  // context for dial
	ready chan struct{}    // closed when pc, err pair is delivered

	// 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 cancelled.
	beforeDial func()
	afterDial  func()

	mu  sync.Mutex // protects pc, err, close(ready)
	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.

func (w *wantConn) waiting() bool

waiting reports whether w is still waiting for an answer (connection or error).

func (w *wantConn) tryDeliver(pc *persistConn, err error) bool

tryDeliver attempts to deliver pc, err to w and reports whether it succeeded.

func (w *wantConn) cancel(t *Transport, err error)

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.

type wantConnQueue struct {
	// 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.
	head    []*wantConn
	headPos int
	tail    []*wantConn
}

A wantConnQueue is a queue of wantConns.

func (q *wantConnQueue) len() int

len returns the number of items in the queue.

func (q *wantConnQueue) pushBack(w *wantConn)

pushBack adds w to the back of the queue.

func (q *wantConnQueue) popFront() *wantConn

popFront removes and returns the wantConn at the front of the queue.

func (q *wantConnQueue) peekFront() *wantConn

peekFront returns the wantConn at the front of the queue without removing it.

func (q *wantConnQueue) cleanFront() (cleaned bool)

cleanFront pops any wantConns that are no longer waiting from the head of the queue, reporting whether any were popped.

type erringRoundTripper interface {
	RoundTripErr() error
}
type persistConnWriter struct {
	pc *persistConn
}

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.

func (w persistConnWriter) Write(p []byte) (n int, err error)
func (w persistConnWriter) ReadFrom(r io.Reader) (n int64, err error)

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.

type connectMethod struct {
	_            incomparable
	proxyURL     *url.URL // nil for no proxy, else full proxy URL
	targetScheme string   // "http" or "https"
	// 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.
	targetAddr string
	onlyH1     bool // whether to disable HTTP/2 and force HTTP/1
}

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](http://proxy.com)|https|foo.com    http to proxy, then CONNECT to foo.com
[http://proxy.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://proxy.com)|https|foo.com   https to proxy, then CONNECT to foo.com
[https://proxy.com](https://proxy.com)|http            https to proxy, http to anywhere after that

func (cm *connectMethod) proxyAuth() string

proxyAuth returns the Proxy-Authorization header to set on requests, if applicable.

func (cm *connectMethod) key() connectMethodKey
func (cm *connectMethod) scheme() string

scheme returns the first hop scheme: http, https, or socks5

func (cm *connectMethod) addr() string

addr returns the first hop "host:port" to which we need to TCP connect.

func (cm *connectMethod) tlsHost() string

tlsHost returns the host name to match against the peer's TLS certificate.

type connectMethodKey struct {
	proxy, scheme, addr string
	onlyH1              bool
}

connectMethodKey is the map key version of connectMethod, with a stringified proxy URL (or the empty string) instead of a pointer to a URL.

func (k connectMethodKey) String() string
type persistConn struct {
	// 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.
	alt RoundTripper

	t         *Transport
	cacheKey  connectMethodKey
	conn      net.Conn
	tlsState  *tls.ConnectionState
	br        *bufio.Reader       // from conn
	bw        *bufio.Writer       // to conn
	nwrite    int64               // bytes written
	reqch     chan requestAndChan // written by roundTrip; read by readLoop
	writech   chan writeRequest   // written by roundTrip; read by writeLoop
	closech   chan struct{}       // closed when conn closed
	isProxy   bool
	sawEOF    bool  // whether we've seen EOF from conn; owned by readLoop
	readLimit int64 // bytes allowed to be read; owned by readLoop
	// 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.
	writeErrCh chan error

	writeLoopDone chan struct{} // closed when write loop ends

	// Both guarded by Transport.idleMu:
	idleAt    time.Time   // time it last become idle
	idleTimer *time.Timer // holding an AfterFunc to close it

	mu                   sync.Mutex // guards following fields
	numExpectedResponses int
	closed               error // set non-nil when conn is closed, before closech is closed
	canceledErr          error // set non-nil if conn is canceled
	broken               bool  // an error has happened on this connection; marked broken so it's not reused.
	reused               bool  // whether conn has had successful request/response and is being reused.
	// 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)
	mutateHeaderFunc func(Header)
}

persistConn wraps a connection, usually a persistent one (but may be used for non-keep-alive requests as well)

func (pc *persistConn) shouldRetryRequest(req *Request, err error) bool

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.

func (pconn *persistConn) addTLS(name string, trace *httptrace.ClientTrace) 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.

func (pc *persistConn) maxHeaderResponseSize() int64
func (pc *persistConn) Read(p []byte) (n int, err error)
func (pc *persistConn) isBroken() bool

isBroken reports whether this connection is in a known broken state.

func (pc *persistConn) canceled() error

canceled returns non-nil if the connection was closed due to CancelRequest or due to context cancellation.

func (pc *persistConn) isReused() bool

isReused reports whether this connection has been used before.

func (pc *persistConn) gotIdleConnTrace(idleAt time.Time) (t httptrace.GotConnInfo)
func (pc *persistConn) cancelRequest(err error)
func (pc *persistConn) closeConnIfStillIdle()

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.

func (pc *persistConn) mapRoundTripError(req *transportRequest, startBytesWritten int64, err error) error

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.

func (pc *persistConn) readLoop()
func (pc *persistConn) readLoopPeekFailLocked(peekErr error)
func (pc *persistConn) readResponse(rc requestAndChan, trace *httptrace.ClientTrace) (resp *Response, err 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.

func (pc *persistConn) waitForContinue(continueCh <-chan struct{}) func() bool

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.

func (pc *persistConn) writeLoop()
func (pc *persistConn) wroteRequest() bool

wroteRequest is a check before recycling a connection that the previous write (from writeLoop above) happened and was successful.

func (pc *persistConn) roundTrip(req *transportRequest) (resp *Response, err error)
func (pc *persistConn) markReused()

markReused marks this connection as having been successfully used for a request and response.

func (pc *persistConn) close(err error)

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.

func (pc *persistConn) closeLocked(err error)
type readWriteCloserBody struct {
	_  incomparable
	br *bufio.Reader // used until empty
	io.ReadWriteCloser
}

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.

func (b *readWriteCloserBody) Read(p []byte) (n int, err error)
type nothingWrittenError struct {
	error
}

nothingWrittenError wraps a write errors which ended up writing zero bytes.

type responseAndError struct {
	_   incomparable
	res *Response // else use this response (see res method)
	err error
}

responseAndError is how the goroutine reading from an HTTP/1 server communicates with the goroutine doing the RoundTrip.

type requestAndChan struct {
	_         incomparable
	req       *Request
	cancelKey cancelKey
	ch        chan responseAndError // unbuffered; always send in select on callerGone

	// 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.
	addedGzip bool

	// 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.
	continueCh chan<- struct{}

	callerGone <-chan struct{} // closed when roundTrip caller has returned
}
type writeRequest struct {
	req *transportRequest
	ch  chan<- error

	// Optional blocking chan for Expect: 100-continue (for receive).
	// If not nil, writeLoop blocks sending request body until
	// it receives from this chan.
	continueCh <-chan struct{}
}

A writeRequest is sent by the readLoop'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.

type httpError struct {
	err     string
	timeout bool
}
func (e *httpError) Error() string
func (e *httpError) Timeout() bool
func (e *httpError) Temporary() bool
type tLogKey struct{}

tLogKey is a context WithValue key for test debugging contexts containing a t.Logf func. See export_test.go's Request.WithT method.

type bodyEOFSignal struct {
	body         io.ReadCloser
	mu           sync.Mutex        // guards following 4 fields
	closed       bool              // whether Close has been called
	rerr         error             // sticky Read error
	fn           func(error) error // err will be nil on Read io.EOF
	earlyCloseFn func() error      // optional alt Close func used if io.EOF not seen
}

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.

func (es *bodyEOFSignal) Read(p []byte) (n int, err error)
func (es *bodyEOFSignal) Close() error
func (es *bodyEOFSignal) condfn(err error) error

caller must hold es.mu.

type gzipReader struct {
	_    incomparable
	body *bodyEOFSignal // underlying HTTP/1 response body framing
	zr   *gzip.Reader   // lazily-initialized gzip reader
	zerr error          // any error from gzip.NewReader; sticky
}

gzipReader wraps a response body so it can lazily call gzip.NewReader on the first call to Read

func (gz *gzipReader) Read(p []byte) (n int, err error)
func (gz *gzipReader) Close() error
type tlsHandshakeTimeoutError struct{}
func (tlsHandshakeTimeoutError) Timeout() bool
func (tlsHandshakeTimeoutError) Temporary() bool
func (tlsHandshakeTimeoutError) Error() string
type fakeLocker struct{}

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.

func (fakeLocker) Lock()
func (fakeLocker) Unlock()
type connLRU struct {
	ll *list.List // list.Element.Value type is of *persistConn
	m  map[*persistConn]*list.Element
}
func (cl *connLRU) add(pc *persistConn)

add adds pc to the head of the linked list.

func (cl *connLRU) removeOldest() *persistConn
func (cl *connLRU) remove(pc *persistConn)

remove removes pc from cl.

func (cl *connLRU) len() int

len returns the number of items in the cache.

type headerOnlyResponseWriter Header
func (ho headerOnlyResponseWriter) Header() Header
func (ho headerOnlyResponseWriter) Write([]byte) (int, error)
func (ho headerOnlyResponseWriter) WriteHeader(int)
type hasTokenTest struct {
	header string
	token  string
	want   bool
}
type reqTest struct {
	Raw     string
	Req     *Request
	Body    string
	Trailer Header
	Error   string
}
type reqWriteTest struct {
	Req  Request
	Body interface{} // optional []byte or func() io.ReadCloser to populate Req.Body

	// Any of these three may be empty to skip that test.
	WantWrite string // Request.Write
	WantProxy string // Request.WriteProxy

	WantError error // wanted error from Request.Write
}
type testCase struct {
	method string
	clen   int64 // ContentLength
	body   io.ReadCloser
	want   func(string) error

	// optional:
	init         func(*testCase)
	afterReqRead func()
}
type closeChecker struct {
	io.Reader
	closed bool
}
func (rc *closeChecker) Close() error
type writerFunc func([]byte) (int, error)
func (f writerFunc) Write(p []byte) (int, error)
type delegateReader struct {
	c chan io.Reader
	r io.Reader // nil until received from c
}

delegateReader is a reader that delegates to another reader, once it arrives on a channel.

func (r *delegateReader) Read(p []byte) (int, error)
type dumpConn struct {
	io.Writer
	io.Reader
}

dumpConn is a net.Conn that writes to Writer and reads from Reader.

func (c *dumpConn) Close() error
func (c *dumpConn) LocalAddr() net.Addr
func (c *dumpConn) RemoteAddr() net.Addr
func (c *dumpConn) SetDeadline(t time.Time) error
func (c *dumpConn) SetReadDeadline(t time.Time) error
func (c *dumpConn) SetWriteDeadline(t time.Time) error
type respTest struct {
	Raw  string
	Resp Response
	Body string
}
type readerAndCloser struct {
	io.Reader
	io.Closer
}
type responseLocationTest struct {
	location string // Response's Location header or ""
	requrl   string // Response.Request.URL or ""
	want     string
	wantErr  error
}
type testCase struct {
	name    string // optional, defaults to in
	in      string
	wantErr interface{} // nil, err value, or string substring
}
type respWriteTest struct {
	Resp Response
	Raw  string
}
type mockTransferWriter struct {
	CalledReader io.Reader
	WriteCalled  bool
}
func (w *mockTransferWriter) ReadFrom(r io.Reader) (int64, error)
func (w *mockTransferWriter) Write(p []byte) (int, error)
type issue22091Error struct{}

issue22091Error acts like a golang.org/x/net/http2.ErrNoCachedConn.

func (issue22091Error) IsHTTP2NoCachedConnError()
func (issue22091Error) Error() string
type roundTripFunc func(r *Request) (*Response, error)
func (f roundTripFunc) RoundTrip(r *Request) (*Response, error)
func refererForURL(lastReq, newReq *url.URL) string

refererForURL returns a referer without any authentication info or an empty string if lastReq scheme is https and newReq scheme is http.

func timeBeforeContextDeadline(t time.Time, ctx context.Context) bool

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

func knownRoundTripperImpl(rt RoundTripper, req *Request) bool

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.

func setRequestCancel(req *Request, rt RoundTripper, deadline time.Time) (stopTimer func(), didTimeout func() bool)

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.

func basicAuth(username, password string) string

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.

func alwaysFalse() bool
func redirectBehavior(reqMethod string, resp *Response, ireq *Request) (redirectMethod string, shouldRedirect, includeBody bool)

redirectBehavior describes what should happen when the client encounters a 3xx status code from the server

func urlErrorOp(method string) string

urlErrorOp returns the (*url.Error).Op value to use for the provided (*Request).Method value.

func defaultCheckRedirect(req *Request, via []*Request) error
func shouldCopyHeaderOnRedirect(headerKey string, initial, dest *url.URL) bool
func isDomainOrSubdomain(sub, parent string) bool

isDomainOrSubdomain reports whether sub is a subdomain (or exact match) of the parent domain.

Both domains must already be in canonical form.

func stripPassword(u *url.URL) string
func cloneURLValues(v url.Values) url.Values
func cloneURL(u *url.URL) *url.URL
func cloneMultipartForm(f *multipart.Form) *multipart.Form
func cloneMultipartFileHeader(fh *multipart.FileHeader) *multipart.FileHeader
func readSetCookies(h Header) []*Cookie

readSetCookies parses all "Set-Cookie" values from the header h and returns the successfully parsed Cookies.

func SetCookie(w ResponseWriter, cookie *Cookie)

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

func readCookies(h Header, filter string) []*Cookie

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

func validCookieDomain(v string) bool

validCookieDomain reports whether v is a valid cookie domain-value.

func validCookieExpires(t time.Time) bool

validCookieExpires reports whether v is a valid cookie expires-value.

func isCookieDomainName(s string) bool

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.

func sanitizeCookieName(n string) string
func sanitizeCookieValue(v string) string

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.

func validCookieValueByte(b byte) bool
func sanitizeCookiePath(v string) string

path-av = "Path=" path-value path-value = <any CHAR except CTLs or ";">

func validCookiePathByte(b byte) bool
func sanitizeOrWarn(fieldName string, valid func(byte) bool, v string) string
func parseCookieValue(raw string, allowDoubleQuote bool) (string, bool)
func isCookieNameValid(raw string) bool
func mapDirOpenError(originalErr error, name string) error

mapDirOpenError 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 Issue 18984.

func dirList(w ResponseWriter, r *Request, f File)
func ServeContent(w ResponseWriter, req *Request, name string, modtime time.Time, content io.ReadSeeker)

ServeContent replies to the request using the content in the provided ReadSeeker. The main benefit of ServeContent over io.Copy is that it handles Range requests properly, sets the MIME type, and handles If-Match, If-Unmodified-Since, If-None-Match, If-Modified-Since, and If-Range requests.

If the response's Content-Type header is not set, ServeContent first tries to deduce the type from name's file extension and, if that fails, falls back to reading the first block of the content and passing it to DetectContentType. The name is otherwise unused; in particular it can be empty and is never sent in the response.

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

The content's Seek method must work: ServeContent uses a seek to the end of the content to determine its size.

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

Note that *os.File implements the io.ReadSeeker interface.

func serveContent(w ResponseWriter, r *Request, name string, modtime time.Time, sizeFunc func() (int64, error), content io.ReadSeeker)

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.

func scanETag(s string) (etag string, remain string)

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 "", "".

func etagStrongMatch(a, b string) bool

etagStrongMatch reports whether a and b match using strong ETag comparison. Assumes a and b are valid ETags.

func etagWeakMatch(a, b string) bool

etagWeakMatch reports whether a and b match using weak ETag comparison. Assumes a and b are valid ETags.

func isZeroTime(t time.Time) bool

isZeroTime reports whether t is obviously unspecified (either zero or Unix()=0).

func setLastModified(w ResponseWriter, modtime time.Time)
func writeNotModified(w ResponseWriter)
func checkPreconditions(w ResponseWriter, r *Request, modtime time.Time) (done bool, rangeHeader string)

checkPreconditions evaluates request preconditions and reports whether a precondition resulted in sending StatusNotModified or StatusPreconditionFailed.

func serveFile(w ResponseWriter, r *Request, fs FileSystem, name string, redirect bool)

name is '/'-separated, not filepath.Separator.

func toHTTPError(err error) (msg string, httpStatus int)

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.

func localRedirect(w ResponseWriter, r *Request, newPath string)

localRedirect gives a Moved Permanently response. It does not convert relative paths to absolute paths like Redirect does.

func ServeFile(w ResponseWriter, r *Request, name string)

ServeFile replies to the request with the contents of the named file or directory.

If the provided file or directory name is a relative path, it is interpreted relative to the current directory and may ascend to parent directories. If the provided name is constructed from user input, it should be sanitized before calling ServeFile.

As a precaution, ServeFile will reject requests where r.URL.Path contains a ".." path element; this protects against callers who might unsafely use filepath.Join on r.URL.Path without sanitizing it and then use that filepath.Join result as the name argument.

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

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

func containsDotDot(v string) bool
func isSlashRune(r rune) bool
func parseRange(s string, size int64) ([]httpRange, error)

parseRange parses a Range header string as per RFC 7233. errNoOverlap is returned if none of the ranges overlap.

func rangesMIMESize(ranges []httpRange, contentType string, contentSize int64) (encSize int64)

rangesMIMESize returns the number of bytes it takes to encode the provided ranges as a multipart response.

func sumRangesSize(ranges []httpRange) (size int64)
func http2isBadCipher(cipher uint16) bool

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"

func http2filterOutClientConn(in []*http2ClientConn, exclude *http2ClientConn) []*http2ClientConn
func http2getDataBufferChunk(size int64) []byte
func http2putDataBufferChunk(p []byte)
func http2terminalReadFrameError(err error) bool

terminalReadFrameError reports whether err is an unrecoverable error from ReadFrame and no other frames should be read.

func http2validStreamIDOrZero(streamID uint32) bool
func http2validStreamID(streamID uint32) bool
func http2readByte(p []byte) (remain []byte, b byte, err error)
func http2readUint32(p []byte) (remain []byte, v uint32, err error)
func http2summarizeFrame(f http2Frame) string
func http2traceHasWroteHeaderField(trace *httptrace.ClientTrace) bool
func http2traceWroteHeaderField(trace *httptrace.ClientTrace, k, v string)
func http2traceGot1xxResponseFunc(trace *httptrace.ClientTrace) func(int, textproto.MIMEHeader) error
func http2curGoroutineID() uint64
func http2parseUintBytes(s []byte, base int, bitSize int) (n uint64, err error)

parseUintBytes is like strconv.ParseUint, but using a []byte.

func http2cutoff64(base int) uint64

Return the first number n such that n*base >= 1<<64.

func http2buildCommonHeaderMapsOnce()
func http2buildCommonHeaderMaps()
func http2lowerHeader(v string) string
func init()
func http2validWireHeaderFieldName(v string) bool

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

func http2httpCodeString(code int) string
func http2mustUint31(v int32) uint32
func http2bodyAllowedForStatus(status int) bool

bodyAllowedForStatus reports whether a given response status code permits a body. See RFC 7230, section 3.3.

func http2validPseudoPath(v string) bool

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.

func http2ConfigureServer(s *Server, conf *http2Server) error

ConfigureServer adds HTTP/2 support to a net/http Server.

The configuration conf may be nil.

ConfigureServer must be called before s begins serving.

func http2serverConnBaseContext(c net.Conn, opts *http2ServeConnOpts) (ctx context.Context, cancel func())
func http2errno(v error) uintptr

errno returns v's underlying uintptr, else 0.

TODO: remove this helper function once http2 can use build tags. See comment in isClosedConnError.

func http2isClosedConnError(err error) bool

isClosedConnError reports whether err is an error from use of a closed network connection.

func http2checkPriority(streamID uint32, p http2PriorityParam) error
func http2handleHeaderListTooLong(w ResponseWriter, r *Request)
func http2checkWriteHeaderCode(code int)

checkWriteHeaderCode is a copy of net/http's checkWriteHeaderCode.

func http2foreachHeaderElement(v string, fn func(string))

foreachHeaderElement splits v according to the "#rule" construction in RFC 7230 section 7 and calls fn for each non-empty element.

func http2checkValidHTTP2RequestHeaders(h Header) error

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.

func http2h1ServerKeepAlivesDisabled(hs *Server) bool

h1ServerKeepAlivesDisabled reports whether hs has its keep-alives disabled. See comments on h1ServerShutdownChan above for why the code is written this way.

func http2ConfigureTransport(t1 *Transport) error

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.

func http2awaitRequestCancel(req *Request, done <-chan struct{}) error

awaitRequestCancel waits for the user to cancel a request or for the done channel to be signaled. A non-nil error is returned only if the request was canceled.

func http2isNoCachedConnError(err error) bool

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.

func http2authorityAddr(scheme string, authority string) (addr string)

authorityAddr returns a given authority (a host/IP, or host:port / ip:port) and returns a host:port. The port 443 is added if needed.

func http2canRetryError(err error) bool
func http2commaSeparatedTrailers(req *Request) (string, error)
func http2checkConnHeaders(req *Request) error

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.

func http2actualContentLength(req *Request) int64

actualContentLength returns a sanitized version of req.ContentLength, where 0 actually means zero (not unknown) and -1 means unknown.

func http2shouldSendReqContentLength(method string, contentLength int64) bool

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.

func http2isEOFOrNetReadError(err error) bool
func http2strSliceContains(ss []string, s string) bool
func http2isConnectionCloseRequest(req *Request) bool

isConnectionCloseRequest reports whether req should use its own connection for a single request and then close the connection.

func http2registerHTTPSProtocol(t *Transport, rt http2noDialH2RoundTripper) (err error)

registerHTTPSProtocol calls Transport.RegisterProtocol but converting panics into errors.

func http2traceGetConn(req *Request, hostPort string)
func http2traceGotConn(req *Request, cc *http2ClientConn, reused bool)
func http2traceWroteHeaders(trace *httptrace.ClientTrace)
func http2traceGot100Continue(trace *httptrace.ClientTrace)
func http2traceWait100Continue(trace *httptrace.ClientTrace)
func http2traceWroteRequest(trace *httptrace.ClientTrace, err error)
func http2traceFirstResponseByte(trace *httptrace.ClientTrace)
func http2writeEndsStream(w http2writeFramer) bool

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

func http2splitHeaderBlock(ctx http2writeContext, headerBlock []byte, fn func(ctx http2writeContext, frag []byte, firstFrag, lastFrag bool) error) error

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.

func http2encKV(enc *hpack.Encoder, k, v string)
func http2encodeHeaders(enc *hpack.Encoder, h Header, keys []string)

encodeHeaders encodes an http.Header. If keys is not nil, then (k, h[k]) is encoded only if k is in keys.

func ParseTime(text string) (t time.Time, err error)

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

func CanonicalHeaderKey(s string) string

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

func hasToken(v, token string) bool

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.

func isTokenBoundary(b byte) bool
func hasPort(s string) bool

Given a string of the form "host", "host:port", or "[ipv6::address]:port", return true if the string includes a port.

func removeEmptyPort(host string) string

removeEmptyPort strips the empty port in ":port" to "" as mandated by RFC 3986 Section 6.2.3.

func isNotToken(r rune) bool
func isASCII(s string) bool
func stringContainsCTLByte(s string) bool

stringContainsCTLByte reports whether s contains any ASCII control character.

func hexEscapeNonASCII(s string) string
func badStringError(what, val string) error
func valueOrDefault(value, def string) string

Return value if nonempty, def otherwise.

func idnaASCII(v string) (string, error)
func cleanHost(in string) string

cleanHost cleans up the host sent in request's Host header.

It both strips anything after '/' or ' ', and puts the value into Punycode form, if necessary.

Ideally we'd clean the Host header according to the spec:

[https://tools.ietf.org/html/rfc7230#section-5.4](https://tools.ietf.org/html/rfc7230#section-5.4) (Host = uri-host [ ":" port ]")
[https://tools.ietf.org/html/rfc7230#section-2.7](https://tools.ietf.org/html/rfc7230#section-2.7) (uri-host -> rfc3986's host)
[https://tools.ietf.org/html/rfc3986#section-3.2.2](https://tools.ietf.org/html/rfc3986#section-3.2.2) (definition of host)

But practically, what we are trying to avoid is the situation in issue 11206, where a malformed Host header used in the proxy context would create a bad request. So it is enough to just truncate at the first offending character.

func removeZone(host string) string

removeZone removes IPv6 zone identifier from host. E.g., "[fe80::1%en0]:8080" to "[fe80::1]:8080"

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

ParseHTTPVersion parses an HTTP version string. "HTTP/1.0" returns (1, 0, true).

func validMethod(method string) bool
func parseBasicAuth(auth string) (username, password string, ok bool)

parseBasicAuth parses an HTTP Basic Authentication string. "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" returns ("Aladdin", "open sesame", true).

func parseRequestLine(line string) (method, requestURI, proto string, ok bool)

parseRequestLine parses "GET /foo HTTP/1.1" into its three parts.

func newTextprotoReader(br *bufio.Reader) *textproto.Reader
func putTextprotoReader(r *textproto.Reader)
func MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser

MaxBytesReader is similar to io.LimitReader but is intended for limiting the size of incoming request bodies. In contrast to io.LimitReader, MaxBytesReader's result is a ReadCloser, returns a non-EOF error for a Read beyond the limit, and closes the underlying reader when its Close method is called.

MaxBytesReader prevents clients from accidentally or maliciously sending a large request and wasting server resources.

func copyValues(dst, src url.Values)
func parsePostForm(r *Request) (vs url.Values, err error)
func requestMethodUsuallyLacksBody(method string) bool

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.

func fixPragmaCacheControl(header Header)

RFC 7234, section 5.4: Should treat

Pragma: no-cache

like

Cache-Control: no-cache

func isProtocolSwitchResponse(code int, h Header) bool

isProtocolSwitchResponse reports whether the response code and response header indicate a successful protocol upgrade response.

func isProtocolSwitchHeader(h Header) bool

isProtocolSwitchHeader reports whether the request or response header is for a protocol switch.

func bufioWriterPool(size int) *sync.Pool
func newBufioReader(r io.Reader) *bufio.Reader
func putBufioReader(br *bufio.Reader)
func newBufioWriterSize(w io.Writer, size int) *bufio.Writer
func putBufioWriter(bw *bufio.Writer)
func appendTime(b []byte, t time.Time) []byte

appendTime is a non-allocating version of []byte(t.UTC().Format(TimeFormat))

func http1ServerSupportsRequest(req *Request) bool

http1ServerSupportsRequest reports whether Go's HTTP/1.x server supports the given request.

func checkWriteHeaderCode(code int)
func relevantCaller() runtime.Frame

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.

func foreachHeaderElement(v string, fn func(string))

foreachHeaderElement splits v according to the "#rule" construction in RFC 7230 section 7 and calls fn for each non-empty element.

func writeStatusLine(bw *bufio.Writer, is11 bool, code int, scratch []byte)

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.

func validNextProto(proto string) bool

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.

func badRequestError(e string) error

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.

func isCommonNetReadError(err error) bool

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.

func registerOnHitEOF(rc io.ReadCloser, fn func())
func requestBodyRemains(rc io.ReadCloser) bool

requestBodyRemains reports whether future calls to Read on rc might yield more data.

func Error(w ResponseWriter, error string, code int)

Error replies to the request with the specified error message and HTTP code. It does not otherwise end the request; the caller should ensure no further writes are done to w. The error message should be plain text.

func NotFound(w ResponseWriter, r *Request)

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

func Redirect(w ResponseWriter, r *Request, url string, code int)

Redirect replies to the request with a redirect to url, which may be a path relative to the request path.

The provided code should be in the 3xx range and is usually StatusMovedPermanently, StatusFound or StatusSeeOther.

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

func htmlEscape(s string) string
func cleanPath(p string) string

cleanPath returns the canonical path for p, eliminating . and .. elements.

func stripHostPort(h string) string

stripHostPort returns h without any trailing ":".

func appendSorted(es []muxEntry, e muxEntry) []muxEntry
func Handle(pattern string, handler Handler)

Handle registers the handler for the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched.

func HandleFunc(pattern string, handler func(ResponseWriter, *Request))

HandleFunc registers the handler function for the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched.

func Serve(l net.Listener, handler Handler) error

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

The handler is typically nil, in which case the DefaultServeMux is used.

HTTP/2 support is only enabled if the Listener returns *tls.Conn connections and they were configured with "h2" in the TLS Config.NextProtos.

Serve always returns a non-nil error.

func ServeTLS(l net.Listener, handler Handler, certFile, keyFile string) error

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

The handler is typically nil, in which case the DefaultServeMux is used.

Additionally, files containing a certificate and matching private key for the server must be provided. If the certificate is signed by a certificate authority, the certFile should be the concatenation of the server's certificate, any intermediates, and the CA's certificate.

ServeTLS always returns a non-nil error.

func logf(r *Request, format string, args ...interface{})

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.

func ListenAndServe(addr string, handler Handler) error

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

The handler is typically nil, in which case the DefaultServeMux is used.

ListenAndServe always returns a non-nil error.

func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error

ListenAndServeTLS acts identically to ListenAndServe, except that it expects HTTPS connections. Additionally, files containing a certificate and matching private key for the server must be provided. If the certificate is signed by a certificate authority, the certFile should be the concatenation of the server's certificate, any intermediates, and the CA's certificate.

func newLoggingConn(baseName string, c net.Conn) net.Conn
func numLeadingCRorLF(v []byte) (n int)
func strSliceContains(ss []string, s string) bool
func tlsRecordHeaderLooksLikeHTTP(hdr [5]byte) bool

tlsRecordHeaderLooksLikeHTTP reports whether a TLS record header looks like it might've been a misdirected plaintext HTTP request.

func DetectContentType(data []byte) string

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

func isWS(b byte) bool

isWS reports whether the provided byte is a whitespace byte (0xWS) as defined in https://mimesniff.spec.whatwg.org/#terminology.

func isTT(b byte) bool

isTT reports whether the provided byte is a tag-terminating byte (0xTT) as defined in https://mimesniff.spec.whatwg.org/#terminology.

func sockssplitHostPort(address string) (string, int, error)
func StatusText(code int) string

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

func noResponseBodyExpected(requestMethod string) bool
func bodyAllowedForStatus(status int) bool

bodyAllowedForStatus reports whether a given response status code permits a body. See RFC 7230, section 3.3.

func suppressedHeaders(status int) []string
func readTransfer(msg interface{}, r *bufio.Reader) (err error)

msg is *Request or *Response.

func chunked(te []string) bool

Checks whether chunked is part of the encodings stack

func isIdentity(te []string) bool

Checks whether the encoding is explicitly "identity".

func isUnsupportedTEError(err error) bool

isUnsupportedTEError checks if the error is of type unsupportedTEError. It is usually invoked with a non-nil err.

func fixLength(isResponse bool, status int, requestMethod string, header Header, chunked bool) (int64, error)

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.

func shouldClose(major, minor int, header Header, removeCloseHeader bool) bool

Determine whether to hang up after sending a request and body, or receiving a response and body 'header' is the request headers

func seeUpcomingDoubleCRLF(r *bufio.Reader) bool
func mergeSetHeader(dst *Header, src Header)
func parseContentLength(cl string) (int64, error)

parseContentLength trims whitespace from s and returns -1 if no value is set, or the value if it's >= 0.

func isKnownInMemoryReader(r io.Reader) bool

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.

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

ProxyFromEnvironment returns the URL of the proxy to use for a given request, as indicated by the environment variables HTTP_PROXY, HTTPS_PROXY and NO_PROXY (or the lowercase versions thereof). HTTPS_PROXY takes precedence over HTTP_PROXY for https requests.

The environment values may be either a complete URL or a "host[:port]", in which case the "http" scheme is assumed. An error is returned if the value is a different form.

A nil URL and nil error are returned if no proxy is defined in the environment, or a proxy should not be used for the given request, as defined by NO_PROXY.

As a special case, if req.URL.Host is "localhost" (with or without a port number), then a nil URL and nil error will be returned.

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

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

func envProxyFunc() func(*url.URL) (*url.URL, error)

defaultProxyConfig returns a ProxyConfig value looked up from the environment. This mitigates expensive lookups on some platforms (e.g. Windows).

func resetProxyConfig()

resetProxyConfig is used by tests.

func is408Message(buf []byte) bool

is408Message reports whether buf has the prefix of an HTTP 408 Request Timeout response. See golang.org/issue/32310.

func newReadWriteCloserBody(br *bufio.Reader, rwc io.ReadWriteCloser) io.ReadWriteCloser
func nop()
func canonicalAddr(url *url.URL) string

canonicalAddr returns url.Host but always with a ":port" suffix

func cloneTLSConfig(cfg *tls.Config) *tls.Config

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.

func TestWriteSetCookies(t *testing.T)
func TestSetCookie(t *testing.T)
func TestAddCookie(t *testing.T)
func toJSON(v interface{}) string
func TestReadSetCookies(t *testing.T)
func TestReadCookies(t *testing.T)
func TestSetCookieDoubleQuotes(t *testing.T)
func TestCookieSanitizeValue(t *testing.T)
func TestCookieSanitizePath(t *testing.T)
func BenchmarkCookieString(b *testing.B)
func BenchmarkReadSetCookies(b *testing.B)
func BenchmarkReadCookies(b *testing.B)
func init()
func CondSkipHTTP2(t *testing.T)
func SetReadLoopBeforeNextReadHook(f func())
func SetPendingDialHooks(before, after func())

SetPendingDialHooks sets the hooks that run before and after handling pending dials.

func SetTestHookServerServe(fn func(*Server, net.Listener))
func ResetCachedEnvironment()
func unnilTestHook(f *func())

All test hooks must be non-nil so they can be called directly, but the tests use nil to mean hook disabled.

func hookSetter(dst *func()) func(func())
func ExportHttp2ConfigureTransport(t *Transport) error
func ExportSetH2GoawayTimeout(d time.Duration) (restore func())
func ExportCloseTransportConnsAbruptly(tr *Transport)

ExportCloseTransportConnsAbruptly closes all idle connections from tr in an abrupt way, just reaching into the underlying Conns and closing them, without telling the Transport or its persistConns that it's doing so. This is to simulate the server closing connections on the Transport.

func checker(t *testing.T) func(string, error)
func TestFileTransport(t *testing.T)
func TestHeaderWrite(t *testing.T)
func TestParseTime(t *testing.T)
func TestHasToken(t *testing.T)
func TestNilHeaderClone(t *testing.T)
func BenchmarkHeaderWriteSubset(b *testing.B)
func TestHeaderWriteSubsetAllocs(t *testing.T)
func TestCloneOrMakeHeader(t *testing.T)

Issue 34878: test that every call to cloneOrMakeHeader never returns a nil Header.

func TestForeachHeaderElement(t *testing.T)
func TestCleanHost(t *testing.T)
func TestCmdGoNoHTTPServer(t *testing.T)

Test that cmd/go doesn't link in the HTTP server.

This catches accidental dependencies between the HTTP transport and server code.

func TestOmitHTTP2(t *testing.T)

Tests that the nethttpomithttp2 build tag doesn't rot too much, even if there's not a regular builder on it.

func TestOmitHTTP2Vet(t *testing.T)

Tests that the nethttpomithttp2 build tag at least type checks in short mode. The TestOmitHTTP2 test above actually runs tests (in long mode).

func BenchmarkCopyValues(b *testing.B)
func TestCacheKeys(t *testing.T)
func ResetProxyEnv()
func TestParseRange(t *testing.T)
func TestReadRequest(t *testing.T)
func reqBytes(req string) []byte

reqBytes treats req as a request (with \n delimiters) and returns it with \r\n delimiters, ending in \r\n\r\n

func TestReadRequest_Bad(t *testing.T)
func TestRequestWrite(t *testing.T)
func TestRequestWriteTransport(t *testing.T)
func TestRequestWriteClosesBody(t *testing.T)

TestRequestWriteClosesBody tests that Request.Write closes its request.Body. It also indirectly tests NewRequest and that it doesn't wrap an existing Closer inside a NopCloser, and that it serializes it correctly.

func chunk(s string) string
func mustParseURL(s string) *url.URL
func TestRequestWriteError(t *testing.T)

TestRequestWriteError tests the Write err != nil checks in (*Request).write.

func dumpRequestOut(req *Request, onReadHeaders func()) ([]byte, error)

dumpRequestOut is a modified copy of net/http/httputil.DumpRequestOut. Unlike the original, this version doesn't mutate the req.Body and try to restore it. It always dumps the whole body. And it doesn't support https.

func TestReadResponse(t *testing.T)

tests successful calls to ReadResponse, and inspects the returned Response. For error cases, see TestReadResponseErrors below.

func TestWriteResponse(t *testing.T)
func TestReadResponseCloseInMiddle(t *testing.T)

TestReadResponseCloseInMiddle tests that closing a body after reading only part of its contents advances the read to the end of the request, right up until the next request.

func diff(t *testing.T, prefix string, have, want interface{})
func TestLocationResponse(t *testing.T)
func TestResponseStatusStutter(t *testing.T)
func TestResponseContentLengthShortBody(t *testing.T)
func TestReadResponseErrors(t *testing.T)

Test various ReadResponse error cases. (also tests success cases, but mostly it's about errors). This does not test anything involving the bodies. Only the return value from ReadResponse itself.

func matchErr(err error, wantErr interface{}) error

wantErr can be nil, an error value to match exactly, or type string to match a substring.

func TestNeedsSniff(t *testing.T)
func TestResponseWritesOnlySingleConnectionClose(t *testing.T)

A response should only write out single Connection: close header. Tests #19499.

func TestResponseWrite(t *testing.T)
func BenchmarkServerMatch(b *testing.B)
func TestBodyReadBadTrailer(t *testing.T)
func TestFinalChunkedBodyReadEOF(t *testing.T)
func TestDetectInMemoryReaders(t *testing.T)
func TestTransferWriterWriteBodyReaderTypes(t *testing.T)
func TestParseTransferEncoding(t *testing.T)
func TestParseContentLength(t *testing.T)

issue 39017 - disallow Content-Length values such as "+3"

func TestTransportPersistConnReadLoopEOF(t *testing.T)

Issue 15446: incorrect wrapping of errors when server closes an idle connection.

func isTransportReadFromServerError(err error) bool
func newLocalListener(t *testing.T) net.Listener
func TestTransportShouldRetryRequest(t *testing.T)
func TestTransportBodyAltRewind(t *testing.T)

Issue 25009

Package cgi implements CGI (Common Gateway Interface) as specified in RFC 3875.

Note that using CGI means starting a new process to handle each request, which is typically less efficient than using a long-running server. This package is intended primarily for compatibility with existing systems.

Index

const writeLen = 50 << 10
var ok bool
var trailingPort = regexp.MustCompile(`:([0-9]+)$`)
var osDefaultInheritEnv = func() []string {
	switch runtime.GOOS {
	case "darwin", "ios":
		return []string{"DYLD_LIBRARY_PATH"}
	case "linux", "freebsd", "netbsd", "openbsd":
		return []string{"LD_LIBRARY_PATH"}
	case "hpux":
		return []string{"LD_LIBRARY_PATH", "SHLIB_PATH"}
	case "irix":
		return []string{"LD_LIBRARY_PATH", "LD_LIBRARYN32_PATH", "LD_LIBRARY64_PATH"}
	case "illumos", "solaris":
		return []string{"LD_LIBRARY_PATH", "LD_LIBRARY_PATH_32", "LD_LIBRARY_PATH_64"}
	case "windows":
		return []string{"SystemRoot", "COMSPEC", "PATHEXT", "WINDIR"}
	}
	return nil
}()
var cwd, path string
var cwd, path string
var testHookStartProcess func(*os.Process) // nil except for some tests
var tests = ...
var buf bytes.Buffer
var cgiTested, cgiWorks bool
var cgiTested, cgiWorks bool
var buf [5000]byte
var stderr bytes.Buffer
var out bytes.Buffer
var tests = ...
type response struct {
	req            *http.Request
	header         http.Header
	code           int
	wroteHeader    bool
	wroteCGIHeader bool
	bufw           *bufio.Writer
}
func (r *response) Flush()
func (r *response) Header() http.Header
func (r *response) Write(p []byte) (n int, err error)
func (r *response) WriteHeader(code int)
func (r *response) writeCGIHeader(p []byte)

writeCGIHeader finalizes the header sent to the client and writes it to the output. 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.

type Handler struct {
	Path string // path to the CGI executable
	Root string // root URI prefix of handler or empty for "/"

	// Dir specifies the CGI executable's working directory.
	// If Dir is empty, the base directory of Path is used.
	// If Path has no base directory, the current working
	// directory is used.
	Dir string

	Env        []string    // extra environment variables to set, if any, as "key=value"
	InheritEnv []string    // environment variables to inherit from host, as "key"
	Logger     *log.Logger // optional log for errors or nil to use log.Print
	Args       []string    // optional arguments to pass to child process
	Stderr     io.Writer   // optional stderr for the child process; nil means os.Stderr

	// PathLocationHandler specifies the root http Handler that
	// should handle internal redirects when the CGI process
	// returns a Location header value starting with a "/", as
	// specified in RFC 3875 § 6.3.2. This will likely be
	// http.DefaultServeMux.
	//
	// If nil, a CGI response with a local URI path is instead sent
	// back to the client and not redirected internally.
	PathLocationHandler http.Handler
}

Handler runs an executable in a subprocess with a CGI environment.

func (h *Handler) stderr() io.Writer
func (h *Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request)
func (h *Handler) printf(format string, v ...interface{})
func (h *Handler) handleInternalRedirect(rw http.ResponseWriter, req *http.Request, path string)
type customWriterRecorder struct {
	w io.Writer
	*httptest.ResponseRecorder
}
func (r *customWriterRecorder) Write(p []byte) (n int, err error)
type limitWriter struct {
	w io.Writer
	n int
}
func (w *limitWriter) Write(p []byte) (n int, err error)
type neverEnding byte
func (b neverEnding) Read(p []byte) (n int, err error)
func Request() (*http.Request, error)

Request returns the HTTP request as represented in the current environment. This assumes the current program is being run by a web server in a CGI environment. The returned Request's Body is populated, if applicable.

func envMap(env []string) map[string]string
func RequestFromMap(params map[string]string) (*http.Request, error)

RequestFromMap creates an http.Request from CGI variables. The returned Request's Body field is not populated.

func Serve(handler http.Handler) error

Serve executes the provided Handler on the currently active CGI request, if any. If there's no current CGI environment an error is returned. The provided handler may be nil to use http.DefaultServeMux.

func removeLeadingDuplicates(env []string) (ret []string)

removeLeadingDuplicates remove leading duplicate in environments. It's possible to override environment like following.

cgi.Handler{
  ...
  Env: []string{"SCRIPT_FILENAME=foo.php"},
}

func upperCaseAndUnderscore(r rune) rune
func TestRequest(t *testing.T)
func TestRequestWithTLS(t *testing.T)
func TestRequestWithoutHost(t *testing.T)
func TestRequestWithoutRequestURI(t *testing.T)
func TestRequestWithoutRemotePort(t *testing.T)
func TestResponse(t *testing.T)
func newRequest(httpreq string) *http.Request
func runCgiTest(t *testing.T, h *Handler,
	httpreq string,
	expectedMap map[string]string, checks ...func(reqInfo map[string]string)) *httptest.ResponseRecorder
func runResponseChecks(t *testing.T, rw *httptest.ResponseRecorder,
	expectedMap map[string]string, checks ...func(reqInfo map[string]string))
func check(t *testing.T)
func TestCGIBasicGet(t *testing.T)
func TestCGIEnvIPv6(t *testing.T)
func TestCGIBasicGetAbsPath(t *testing.T)
func TestPathInfo(t *testing.T)
func TestPathInfoDirRoot(t *testing.T)
func TestDupHeaders(t *testing.T)
func TestDropProxyHeader(t *testing.T)

Issue 16405: CGI+http.Transport differing uses of HTTP_PROXY. Verify we don't set the HTTP_PROXY environment variable. Hope nobody was depending on it. It's not a known header, though.

func TestPathInfoNoRoot(t *testing.T)
func TestCGIBasicPost(t *testing.T)
func chunk(s string) string
func TestCGIPostChunked(t *testing.T)

The CGI spec doesn't allow chunked requests.

func TestRedirect(t *testing.T)
func TestInternalRedirect(t *testing.T)
func TestCopyError(t *testing.T)

TestCopyError tests that we kill the process if there's an error copying its output. (for example, from the client having gone away)

func TestDirUnix(t *testing.T)
func findPerl(t *testing.T) string
func TestDirWindows(t *testing.T)
func TestEnvOverride(t *testing.T)
func TestHandlerStderr(t *testing.T)
func TestRemoveLeadingDuplicates(t *testing.T)
func TestHostingOurselves(t *testing.T)

This test is a CGI host (testing host.go) that runs its own binary as a child process testing the other half of CGI (child.go).

func TestKillChildAfterCopyError(t *testing.T)

If there's an error copying the child's output to the parent, test that we kill the child.

func TestChildOnlyHeaders(t *testing.T)

Test that a child handler writing only headers works. golang.org/issue/7196

func TestNilRequestBody(t *testing.T)

Test that a child handler does not receive a nil Request Body. golang.org/issue/39190

func TestChildContentType(t *testing.T)
func Test500WithNoHeaders(t *testing.T)

golang.org/issue/7198

func Test500WithNoContentType(t *testing.T)
func Test500WithEmptyHeaders(t *testing.T)
func want500Test(t *testing.T, path string)
func TestBeChildCGIProcess(t *testing.T)

Note: not actually a test.

func isProcessRunning(pid int) bool

Package cookiejar implements an in-memory RFC 6265-compliant http.CookieJar.

Index

const base int32 = 36

These parameter values are specified in section 5.

All computation is done with int32s, so that overflow behavior is identical regardless of whether int is 32-bit or 64-bit.

const damp int32 = 700

These parameter values are specified in section 5.

All computation is done with int32s, so that overflow behavior is identical regardless of whether int is 32-bit or 64-bit.

const initialBias int32 = 72

These parameter values are specified in section 5.

All computation is done with int32s, so that overflow behavior is identical regardless of whether int is 32-bit or 64-bit.

const initialN int32 = 128

These parameter values are specified in section 5.

All computation is done with int32s, so that overflow behavior is identical regardless of whether int is 32-bit or 64-bit.

const skew int32 = 38

These parameter values are specified in section 5.

All computation is done with int32s, so that overflow behavior is identical regardless of whether int is 32-bit or 64-bit.

const tmax int32 = 26

These parameter values are specified in section 5.

All computation is done with int32s, so that overflow behavior is identical regardless of whether int is 32-bit or 64-bit.

const tmin int32 = 1

These parameter values are specified in section 5.

All computation is done with int32s, so that overflow behavior is identical regardless of whether int is 32-bit or 64-bit.

const acePrefix = "xn--"

acePrefix is the ASCII Compatible Encoding prefix.

var selected []entry
var err error
var i int
var errIllegalDomain = errors.New("cookiejar: illegal cookie domain attribute")
var errMalformedDomain = errors.New("cookiejar: malformed cookie domain attribute")
var errNoHostname = errors.New("cookiejar: no host name available (IP only)")
var endOfTime = time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC)

endOfTime is the time when session (non-persistent) cookies expire. This instant is representable in most date/time formats (not just Go's time.Time) and should be far enough in the future.

var tNow = time.Date(2013, 1, 1, 12, 0, 0, 0, time.UTC)

tNow is the synthetic current time used as now during testing.

var hasDotSuffixTests = ...
var canonicalHostTests = ...
var hasPortTests = ...
var jarKeyTests = ...
var jarKeyNilPSLTests = ...
var isIPTests = ...
var defaultPathTests = ...
var domainAndTypeTests = ...
var cs []string

Serialize non-expired entries in the form "name1=val1 name2=val2".

var s []string
var basicsTests = ...

basicsTests contains fundamental tests. Each jarTest has to be performed on a fresh, empty Jar.

var updateAndDeleteTests = ...

updateAndDeleteTests contains jarTests which must be performed on the same Jar.

var chromiumBasicsTests = ...

chromiumBasicsTests contains fundamental tests. Each jarTest has to be performed on a fresh, empty Jar.

var chromiumDomainTests = ...

chromiumDomainTests contains jarTests which must be executed all on the same Jar.

var chromiumDeletionTests = ...

chromiumDeletionTests must be performed all on the same Jar.

var domainHandlingTests = ...

domainHandlingTests tests and documents the rules for domain handling. Each test must be performed on an empty new Jar.

var punycodeTestCases = ...
type PublicSuffixList interface {
	// PublicSuffix returns the public suffix of domain.
	//
	// TODO: specify which of the caller and callee is responsible for IP
	// addresses, for leading and trailing dots, for case sensitivity, and
	// for IDN/Punycode.
	PublicSuffix(domain string) string

	// String returns a description of the source of this public suffix
	// list. The description will typically contain something like a time
	// stamp or version number.
	String() string
}

PublicSuffixList provides the public suffix of a domain. For example:

- the public suffix of "example.com" is "com",
- the public suffix of "foo1.foo2.foo3.co.uk" is "co.uk", and
- the public suffix of "bar.pvt.k12.ma.us" is "pvt.k12.ma.us".

Implementations of PublicSuffixList must be safe for concurrent use by multiple goroutines.

An implementation that always returns "" is valid and may be useful for testing but it is not secure: it means that the HTTP server for foo.com can set a cookie for bar.com.

A public suffix list implementation is in the package golang.org/x/net/publicsuffix.

type Options struct {
	// PublicSuffixList is the public suffix list that determines whether
	// an HTTP server can set a cookie for a domain.
	//
	// A nil value is valid and may be useful for testing but it is not
	// secure: it means that the HTTP server for foo.co.uk can set a cookie
	// for bar.co.uk.
	PublicSuffixList PublicSuffixList
}

Options are the options for creating a new Jar.

type Jar struct {
	psList PublicSuffixList

	// mu locks the remaining fields.
	mu sync.Mutex

	// entries is a set of entries, keyed by their eTLD+1 and subkeyed by
	// their name/domain/path.
	entries map[string]map[string]entry

	// nextSeqNum is the next sequence number assigned to a new cookie
	// created SetCookies.
	nextSeqNum uint64
}

Jar implements the http.CookieJar interface from the net/http package.

func New(o *Options) (*Jar, error)

New returns a new cookie jar. A nil *Options is equivalent to a zero Options.

func newTestJar() *Jar

newTestJar creates an empty Jar with testPSL as the public suffix list.

func (j *Jar) Cookies(u *url.URL) (cookies []*http.Cookie)

Cookies implements the Cookies method of the http.CookieJar interface.

It returns an empty slice if the URL's scheme is not HTTP or HTTPS.

func (j *Jar) cookies(u *url.URL, now time.Time) (cookies []*http.Cookie)

cookies is like Cookies but takes the current time as a parameter.

func (j *Jar) SetCookies(u *url.URL, cookies []*http.Cookie)

SetCookies implements the SetCookies method of the http.CookieJar interface.

It does nothing if the URL's scheme is not HTTP or HTTPS.

func (j *Jar) setCookies(u *url.URL, cookies []*http.Cookie, now time.Time)

setCookies is like SetCookies but takes the current time as parameter.

func (j *Jar) newEntry(c *http.Cookie, now time.Time, defPath, host string) (e entry, remove bool, err error)

newEntry creates an entry from a http.Cookie c. now is the current time and is compared to c.Expires to determine deletion of c. defPath and host are the default-path and the canonical host name of the URL c was received from.

remove records whether the jar should delete this cookie, as it has already expired with respect to now. In this case, e may be incomplete, but it will be valid to call e.id (which depends on e's Name, Domain and Path).

A malformed c.Domain will result in an error.

func (j *Jar) domainAndType(host, domain string) (string, bool, error)

domainAndType determines the cookie's domain and hostOnly attribute.

type entry struct {
	Name       string
	Value      string
	Domain     string
	Path       string
	SameSite   string
	Secure     bool
	HttpOnly   bool
	Persistent bool
	HostOnly   bool
	Expires    time.Time
	Creation   time.Time
	LastAccess time.Time

	// seqNum is a sequence number so that Cookies returns cookies in a
	// deterministic order, even for cookies that have equal Path length and
	// equal Creation time. This simplifies testing.
	seqNum uint64
}

entry is the internal representation of a cookie.

This struct type is not used outside of this package per se, but the exported fields are those of RFC 6265.

func (e *entry) id() string

id returns the domain;path;name triple of e as an id.

func (e *entry) shouldSend(https bool, host, path string) bool

shouldSend determines whether e's cookie qualifies to be included in a request to host/path. It is the caller's responsibility to check if the cookie is expired.

func (e *entry) domainMatch(host string) bool

domainMatch implements "domain-match" of RFC 6265 section 5.1.3.

func (e *entry) pathMatch(requestPath string) bool

pathMatch implements "path-match" according to RFC 6265 section 5.1.4.

type testPSL struct{}

testPSL implements PublicSuffixList with just two rules: "co.uk" and the default rule "*". The implementation has two intentional bugs:

PublicSuffix("www.buggy.psl") == "xy"
PublicSuffix("www2.buggy.psl") == "com"

func (testPSL) String() string
func (testPSL) PublicSuffix(d string) string
type jarTest struct {
	description string   // The description of what this test is supposed to test
	fromURL     string   // The full URL of the request from which Set-Cookie headers where received
	setCookies  []string // All the cookies received from fromURL
	content     string   // The whole (non-expired) content of the jar
	queries     []query  // Queries to test the Jar.Cookies method
}

jarTest encapsulates the following actions on a jar:

1. Perform SetCookies with fromURL and the cookies from setCookies.
   (Done at time tNow + 0 ms.)
2. Check that the entries in the jar matches content.
   (Done at time tNow + 1001 ms.)
3. For each query in tests: Check that Cookies with toURL yields the
   cookies in want.
   (Query n done at tNow + (n+2)*1001 ms.)

func (test jarTest) run(t *testing.T, jar *Jar)

run runs the jarTest.

type query struct {
	toURL string // the URL in the Cookies call
	want  string // the expected list of cookies (order matters)
}

query contains one test of the cookies returned from Jar.Cookies.

func hasDotSuffix(s, suffix string) bool

hasDotSuffix reports whether s ends in "."+suffix.

func canonicalHost(host string) (string, error)

canonicalHost strips port from host if present and returns the canonicalized host name.

func hasPort(host string) bool

hasPort reports whether host contains a port number. host may be a host name, an IPv4 or an IPv6 address.

func jarKey(host string, psl PublicSuffixList) string

jarKey returns the key to use for a jar.

func isIP(host string) bool

isIP reports whether host is an IP address.

func defaultPath(path string) string

defaultPath returns the directory part of an URL's path according to RFC 6265 section 5.1.4.

func encode(prefix, s string) (string, error)

encode encodes a string as specified in section 6.3 and prepends prefix to the result.

The "while h < length(input)" line in the specification becomes "for remaining != 0" in the Go code, because len(s) in Go is in bytes, not runes.

func encodeDigit(digit int32) byte
func adapt(delta, numPoints int32, firstTime bool) int32

adapt is the bias adaptation function specified in section 6.1.

func toASCII(s string) (string, error)

toASCII converts a domain or domain label to its ASCII form. For example, toASCII("bücher.example.com") is "xn--bcher-kva.example.com", and toASCII("golang") is "golang".

func ascii(s string) bool
func TestHasDotSuffix(t *testing.T)
func TestCanonicalHost(t *testing.T)
func TestHasPort(t *testing.T)
func TestJarKey(t *testing.T)
func TestJarKeyNilPSL(t *testing.T)
func TestIsIP(t *testing.T)
func TestDefaultPath(t *testing.T)
func TestDomainAndType(t *testing.T)
func expiresIn(delta int) string

expiresIn creates an expires attribute delta seconds from tNow.

func mustParseURL(s string) *url.URL

mustParseURL parses s to an URL and panics on error.

func TestBasics(t *testing.T)
func TestUpdateAndDelete(t *testing.T)
func TestExpiration(t *testing.T)
func TestChromiumBasics(t *testing.T)
func TestChromiumDomain(t *testing.T)
func TestChromiumDeletion(t *testing.T)
func TestDomainHandling(t *testing.T)
func TestIssue19384(t *testing.T)
func TestPunycode(t *testing.T)

Index

var publicsuffix = ...
type dummypsl struct {
	List cookiejar.PublicSuffixList
}
func (dummypsl) PublicSuffix(domain string) string
func (dummypsl) String() string
func ExampleNew()

Package fcgi implements the FastCGI protocol.

See https://fast-cgi.github.io/ for an unofficial mirror of the original documentation.

Currently only the responder role is supported.

Index

const typeBeginRequest recType = 1
const typeAbortRequest recType = 2
const typeEndRequest recType = 3
const typeParams recType = 4
const typeStdin recType = 5
const typeStdout recType = 6
const typeStderr recType = 7
const typeData recType = 8
const typeGetValues recType = 9
const typeGetValuesResult recType = 10
const typeUnknownType recType = 11
const flagKeepConn = 1

keep the connection between web-server and responder open after request

const maxWrite = 65535 // maximum record body
const maxPad = 255
const roleResponder = iota + 1 // only Responders are implemented.
const roleAuthorizer
const roleFilter
const statusRequestComplete = iota
const statusCantMultiplex
const statusOverloaded
const statusUnknownRole
const want = "\x01\n\x00\x00\x00\x12\x06\x00" +
	"\x0f\x01FCGI_MPXS_CONNS1" +
	"\x00\x00\x00\x00\x00\x00\x01\n\x00\x00\x00\x00\x00\x00"
var rec record
var errCloseConn = errors.New("fcgi: connection should be closed")
var emptyBody = io.NopCloser(strings.NewReader(""))
var ErrRequestAborted = errors.New("fcgi: request aborted by web server")

ErrRequestAborted is returned by Read when a handler attempts to read the body of a request that has been aborted by the web server.

var ErrConnClosed = errors.New("fcgi: connection to web server closed")

ErrConnClosed is returned by Read when a handler attempts to read the body of a request after the connection to the web server has been closed.

var br beginRequest
var body io.ReadCloser
var err error
var pad [maxPad]byte

for padding so we don't have to allocate all the time not synchronized because we don't care what the contents are

var sizeTests = ...
var streamTests = ...
var rec record
var content []byte
var rec record
var streamBeginTypeStdin = bytes.Join([][]byte{

	makeRecord(typeBeginRequest, 1,
		[]byte{0, byte(roleResponder), 0, 0, 0, 0, 0, 0}),

	makeRecord(typeParams, 1, nameValuePair11("REQUEST_METHOD", "GET")),
	makeRecord(typeParams, 1, nameValuePair11("SERVER_PROTOCOL", "HTTP/1.1")),
	makeRecord(typeParams, 1, nil),

	makeRecord(typeStdin, 1, []byte("0123456789abcdef")),
},
	nil)

a series of FastCGI records that start a request and begin sending the request body

var cleanUpTests = ...
var streamFullRequestStdin = bytes.Join([][]byte{

	makeRecord(typeBeginRequest, 1,
		[]byte{0, byte(roleResponder), 0, 0, 0, 0, 0, 0}),

	makeRecord(typeParams, 1, nameValuePair11("REQUEST_METHOD", "GET")),
	makeRecord(typeParams, 1, nameValuePair11("SERVER_PROTOCOL", "HTTP/1.1")),

	makeRecord(typeParams, 1, nameValuePair11("REMOTE_USER", "jane.doe")),
	makeRecord(typeParams, 1, nameValuePair11("QUERY_STRING", "/foo/bar")),
	makeRecord(typeParams, 1, nil),

	makeRecord(typeStdin, 1, []byte("0123456789abcdef")),

	makeRecord(typeEndRequest, 1, nil),
},
	nil)

a series of FastCGI records that start and end a request

var envVarTests = ...
var tests = ...
var resp *response
type request struct {
	pw        *io.PipeWriter
	reqId     uint16
	params    map[string]string
	buf       [1024]byte
	rawParams []byte
	keepConn  bool
}

request holds the state for an in-progress request. As soon as it's complete, it's converted to an http.Request.

func newRequest(reqId uint16, flags uint8) *request
func (r *request) parseParams()

parseParams reads an encoded []byte into Params.

type envVarsContextKey struct{}

envVarsContextKey uniquely identifies a mapping of CGI environment variables to their values in a request context

type response struct {
	req            *request
	header         http.Header
	code           int
	wroteHeader    bool
	wroteCGIHeader bool
	w              *bufWriter
}

response implements http.ResponseWriter.

func newResponse(c *child, req *request) *response
func (r *response) Header() http.Header
func (r *response) Write(p []byte) (n int, err error)
func (r *response) WriteHeader(code int)
func (r *response) writeCGIHeader(p []byte)

writeCGIHeader finalizes the header sent to the client and writes it to the output. 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.

func (r *response) Flush()
func (r *response) Close() error
type child struct {
	conn    *conn
	handler http.Handler

	mu       sync.Mutex          // protects requests:
	requests map[uint16]*request // keyed by request ID
}
func newChild(rwc io.ReadWriteCloser, handler http.Handler) *child
func (c *child) serve()
func (c *child) handleRecord(rec *record) error
func (c *child) serveRequest(req *request, body io.ReadCloser)
func (c *child) cleanUp()
type recType uint8

recType is a record type, as defined by https://web.archive.org/web/20150420080736/http://www.fastcgi.com/drupal/node/6?q=node/22#S8

type header struct {
	Version       uint8
	Type          recType
	Id            uint16
	ContentLength uint16
	PaddingLength uint8
	Reserved      uint8
}
func (h *header) init(recType recType, reqId uint16, contentLength int)
type beginRequest struct {
	role     uint16
	flags    uint8
	reserved [5]uint8
}
func (br *beginRequest) read(content []byte) error
type conn struct {
	mutex sync.Mutex
	rwc   io.ReadWriteCloser

	// to avoid allocations
	buf bytes.Buffer
	h   header
}

conn sends records over rwc

func newConn(rwc io.ReadWriteCloser) *conn
func (c *conn) Close() error
func (c *conn) writeRecord(recType recType, reqId uint16, b []byte) error

writeRecord writes and sends a single record.

func (c *conn) writeEndRequest(reqId uint16, appStatus int, protocolStatus uint8) error
func (c *conn) writePairs(recType recType, reqId uint16, pairs map[string]string) error
type record struct {
	h   header
	buf [maxWrite + maxPad]byte
}
func (rec *record) read(r io.Reader) (err error)
func (r *record) content() []byte
type bufWriter struct {
	closer io.Closer
	*bufio.Writer
}

bufWriter encapsulates bufio.Writer but also closes the underlying stream when Closed.

func newWriter(c *conn, recType recType, reqId uint16) *bufWriter
func (w *bufWriter) Close() error
type streamWriter struct {
	c       *conn
	recType recType
	reqId   uint16
}

streamWriter abstracts out the separation of a stream into discrete records. It only writes maxWrite bytes at a time.

func (w *streamWriter) Write(p []byte) (int, error)
func (w *streamWriter) Close() error
type nilCloser struct {
	io.ReadWriter
}
func (c *nilCloser) Close() error
type writeOnlyConn struct {
	buf []byte
}
func (c *writeOnlyConn) Write(p []byte) (int, error)
func (c *writeOnlyConn) Read(p []byte) (int, error)
func (c *writeOnlyConn) Close() error
type nopWriteCloser struct {
	io.Reader
}
func (nopWriteCloser) Write(buf []byte) (int, error)
func (nopWriteCloser) Close() error
type rwNopCloser struct {
	io.Reader
	io.Writer
}
func (rwNopCloser) Close() error
func filterOutUsedEnvVars(envVars map[string]string) map[string]string

filterOutUsedEnvVars returns a new map of env vars without the variables in the given envVars map that are read for creating each http.Request

func Serve(l net.Listener, handler http.Handler) error

Serve accepts incoming FastCGI connections on the listener l, creating a new goroutine for each. The goroutine reads requests and then calls handler to reply to them. If l is nil, Serve accepts connections from os.Stdin. If handler is nil, http.DefaultServeMux is used.

func ProcessEnv(r *http.Request) map[string]string

ProcessEnv returns FastCGI environment variables associated with the request r for which no effort was made to be included in the request itself - the data is hidden in the request's context. As an example, if REMOTE_USER is set for a request, it will not be found anywhere in r, but it will be included in ProcessEnv's response (via r's context).

func addFastCGIEnvToContext(s string) bool

addFastCGIEnvToContext reports whether to include the FastCGI environment variable s in the http.Request.Context, accessible via ProcessEnv.

func readSize(s []byte) (uint32, int)
func readString(s []byte, size uint32) string
func encodeSize(b []byte, size uint32) int
func TestSize(t *testing.T)
func TestStreams(t *testing.T)
func TestGetValues(t *testing.T)
func nameValuePair11(nameData, valueData string) []byte
func makeRecord(
	recordType recType,
	requestId uint16,
	contentData []byte,
) []byte
func TestChildServeCleansUp(t *testing.T)

Test that child.serve closes the bodies of aborted requests and closes the bodies of all requests before returning. Causes deadlock if either condition isn't met. See issue 6934.

func TestMalformedParams(t *testing.T)

Verifies it doesn't crash. Issue 11824.

func TestChildServeReadsEnvVars(t *testing.T)

Test that environment variables set for a request can be read by a handler. Ensures that variables not set will not be exposed to a handler.

func TestResponseWriterSniffsContentType(t *testing.T)

Package httptest provides utilities for HTTP testing.

Index

const DefaultRemoteAddr = "1.2.3.4"

DefaultRemoteAddr is the default remote address to return in RemoteAddr if an explicit DefaultRemoteAddr isn't set on ResponseRecorder.

var serveFlag string

When debugging a particular http server-based test, this flag lets you run

go test -run=BrokenTest -httptest.serve=127.0.0.1:8000

to start the broken server so you can interact with it manually. We only register this flag if it looks like the caller knows about it and is trying to use it as we don't want to pollute flags and this isn't really part of our API. Don't depend on this.

var buf strings.Builder
var newServers = ...
var s *Server
type ResponseRecorder struct {
	// Code is the HTTP response code set by WriteHeader.
	//
	// Note that if a Handler never calls WriteHeader or Write,
	// this might end up being 0, rather than the implicit
	// http.StatusOK. To get the implicit value, use the Result
	// method.
	Code int

	// HeaderMap contains the headers explicitly set by the Handler.
	// It is an internal detail.
	//
	// Deprecated: HeaderMap exists for historical compatibility
	// and should not be used. To access the headers returned by a handler,
	// use the Response.Header map as returned by the Result method.
	HeaderMap http.Header

	// Body is the buffer to which the Handler's Write calls are sent.
	// If nil, the Writes are silently discarded.
	Body *bytes.Buffer

	// Flushed is whether the Handler called Flush.
	Flushed bool

	result      *http.Response // cache of Result's return value
	snapHeader  http.Header    // snapshot of HeaderMap at first Write
	wroteHeader bool
}

ResponseRecorder is an implementation of http.ResponseWriter that records its mutations for later inspection in tests.

func NewRecorder() *ResponseRecorder

NewRecorder returns an initialized ResponseRecorder.

func (rw *ResponseRecorder) Header() http.Header

Header implements http.ResponseWriter. It returns the response headers to mutate within a handler. To test the headers that were written after a handler completes, use the Result method and see the returned Response value's Header.

func (rw *ResponseRecorder) writeHeader(b []byte, str string)

writeHeader writes a header if it was not written yet and detects Content-Type if needed.

bytes or str are the beginning of the response body. We pass both to avoid unnecessarily generate garbage in rw.WriteString which was created for performance reasons. Non-nil bytes win.

func (rw *ResponseRecorder) Write(buf []byte) (int, error)

Write implements http.ResponseWriter. The data in buf is written to rw.Body, if not nil.

func (rw *ResponseRecorder) WriteString(str string) (int, error)

WriteString implements io.StringWriter. The data in str is written to rw.Body, if not nil.

func (rw *ResponseRecorder) WriteHeader(code int)

WriteHeader implements http.ResponseWriter.

func (rw *ResponseRecorder) Flush()

Flush implements http.Flusher. To test whether Flush was called, see rw.Flushed.

func (rw *ResponseRecorder) Result() *http.Response

Result returns the response generated by the handler.

The returned Response will have at least its StatusCode, Header, Body, and optionally Trailer populated. More fields may be populated in the future, so callers should not DeepEqual the result in tests.

The Response.Header is a snapshot of the headers at the time of the first write call, or at the time of this call, if the handler never did a write.

The Response.Body is guaranteed to be non-nil and Body.Read call is guaranteed to not return any error other than io.EOF.

Result must only be called after the handler has finished running.

type Server struct {
	URL      string // base URL of form http://ipaddr:port with no trailing slash
	Listener net.Listener

	// EnableHTTP2 controls whether HTTP/2 is enabled
	// on the server. It must be set between calling
	// NewUnstartedServer and calling Server.StartTLS.
	EnableHTTP2 bool

	// TLS is the optional TLS configuration, populated with a new config
	// after TLS is started. If set on an unstarted server before StartTLS
	// is called, existing fields are copied into the new config.
	TLS *tls.Config

	// Config may be changed after calling NewUnstartedServer and
	// before Start or StartTLS.
	Config *http.Server

	// certificate is a parsed version of the TLS config certificate, if present.
	certificate *x509.Certificate

	// wg counts the number of outstanding HTTP requests on this server.
	// Close blocks until all requests are finished.
	wg sync.WaitGroup

	mu     sync.Mutex // guards closed and conns
	closed bool
	conns  map[net.Conn]http.ConnState // except terminal states

	// client is configured for use with the server.
	// Its transport is automatically closed when Close is called.
	client *http.Client
}

A Server is an HTTP server listening on a system-chosen port on the local loopback interface, for use in end-to-end HTTP tests.

func NewServer(handler http.Handler) *Server

NewServer starts and returns a new Server. The caller should call Close when finished, to shut it down.

func NewUnstartedServer(handler http.Handler) *Server

NewUnstartedServer returns a new Server but doesn't start it.

After changing its configuration, the caller should call Start or StartTLS.

The caller should call Close when finished, to shut it down.

func NewTLSServer(handler http.Handler) *Server

NewTLSServer starts and returns a new Server using TLS. The caller should call Close when finished, to shut it down.

func (s *Server) Start()

Start starts a server from NewUnstartedServer.

func (s *Server) StartTLS()

StartTLS starts TLS on a server from NewUnstartedServer.

func (s *Server) Close()

Close shuts down the server and blocks until all outstanding requests on this server have completed.

func (s *Server) logCloseHangDebugInfo()
func (s *Server) CloseClientConnections()

CloseClientConnections closes any open HTTP connections to the test Server.

func (s *Server) Certificate() *x509.Certificate

Certificate returns the certificate used by the server, or nil if the server doesn't use TLS.

func (s *Server) Client() *http.Client

Client returns an HTTP client configured for making requests to the server. It is configured to trust the server's TLS test certificate and will close its idle connections on Server.Close.

func (s *Server) goServe()
func (s *Server) wrap()

wrap installs the connection state-tracking hook to know which connections are idle.

func (s *Server) closeConn(c net.Conn)

closeConn closes c. s.mu must be held.

func (s *Server) closeConnChan(c net.Conn, done chan<- struct{})

closeConnChan is like closeConn, but takes an optional channel to receive a value when the goroutine closing c is done.

func (s *Server) forgetConn(c net.Conn)

forgetConn removes c from the set of tracked conns and decrements it from the waitgroup, unless it was previously removed. s.mu must be held.

type closeIdleTransport interface {
	CloseIdleConnections()
}
type checkFunc func(*ResponseRecorder) error
type newServerFunc func(http.Handler) *Server
type onlyCloseListener struct {
	net.Listener
}
func (onlyCloseListener) Close() error
func NewRequest(method, target string, body io.Reader) *http.Request

NewRequest returns a new incoming server Request, suitable for passing to an http.Handler for testing.

The target is the RFC 7230 "request-target": it may be either a path or an absolute URL. If target is an absolute URL, the host name from the URL is used. Otherwise, "example.com" is used.

The TLS field is set to a non-nil dummy value if target has scheme "https".

The Request.Proto is always HTTP/1.1.

An empty method means "GET".

The provided body may be nil. If the body is of type *bytes.Reader, *strings.Reader, or *bytes.Buffer, the Request.ContentLength is set.

NewRequest panics on error for ease of use in testing, where a panic is acceptable.

To generate a client HTTP request instead of a server request, see the NewRequest function in the net/http package.

func parseContentLength(cl string) int64

parseContentLength trims whitespace from s and returns -1 if no value is set, or the value if it's >= 0.

This a modified version of same function found in net/http/transfer.go. This one just ignores an invalid header.

func newLocalListener() net.Listener
func init()
func strSliceContainsPrefix(v []string, pre string) bool
func TestNewRequest(t *testing.T)
func TestRecorder(t *testing.T)
func TestParseContentLength(t *testing.T)

issue 39017 - disallow Content-Length values such as "+3"

func TestServer(t *testing.T)
func testServer(t *testing.T, newServer newServerFunc)
func testGetAfterClose(t *testing.T, newServer newServerFunc)

Issue 12781

func testServerCloseBlocking(t *testing.T, newServer newServerFunc)
func testServerCloseClientConnections(t *testing.T, newServer newServerFunc)

Issue 14290

func testServerClient(t *testing.T, newTLSServer newServerFunc)

Tests that the Server.Client method works and returns an http.Client that can hit NewTLSServer without cert warnings.

func testServerClientTransportType(t *testing.T, newServer newServerFunc)

Tests that the Server.Client.Transport interface is implemented by a *http.Transport.

func testTLSServerClientTransportType(t *testing.T, newTLSServer newServerFunc)

Tests that the TLS Server.Client.Transport interface is implemented by a *http.Transport.

func TestServerZeroValueClose(t *testing.T)

Issue 19729: panic in Server.Close for values created directly without a constructor (so the unexported client field is nil).

func TestTLSServerWithHTTP2(t *testing.T)

Index

func ExampleResponseRecorder()
func ExampleServer()
func ExampleServer_hTTP2()
func ExampleNewTLSServer()

Package httptrace provides mechanisms to trace the events within HTTP client requests.

Index

var buf bytes.Buffer
var buf bytes.Buffer
var testNum int
type clientEventContextKey struct{}

unique type to prevent assignment.

type ClientTrace struct {
	// GetConn is called before a connection is created or
	// retrieved from an idle pool. The hostPort is the
	// "host:port" of the target or proxy. GetConn is called even
	// if there's already an idle cached connection available.
	GetConn func(hostPort string)

	// GotConn is called after a successful connection is
	// obtained. There is no hook for failure to obtain a
	// connection; instead, use the error from
	// Transport.RoundTrip.
	GotConn func(GotConnInfo)

	// PutIdleConn is called when the connection is returned to
	// the idle pool. If err is nil, the connection was
	// successfully returned to the idle pool. If err is non-nil,
	// it describes why not. PutIdleConn is not called if
	// connection reuse is disabled via Transport.DisableKeepAlives.
	// PutIdleConn is called before the caller's Response.Body.Close
	// call returns.
	// For HTTP/2, this hook is not currently used.
	PutIdleConn func(err error)

	// GotFirstResponseByte is called when the first byte of the response
	// headers is available.
	GotFirstResponseByte func()

	// Got100Continue is called if the server replies with a "100
	// Continue" response.
	Got100Continue func()

	// Got1xxResponse is called for each 1xx informational response header
	// returned before the final non-1xx response. Got1xxResponse is called
	// for "100 Continue" responses, even if Got100Continue is also defined.
	// If it returns an error, the client request is aborted with that error value.
	Got1xxResponse func(code int, header textproto.MIMEHeader) error

	// DNSStart is called when a DNS lookup begins.
	DNSStart func(DNSStartInfo)

	// DNSDone is called when a DNS lookup ends.
	DNSDone func(DNSDoneInfo)

	// ConnectStart is called when a new connection's Dial begins.
	// If net.Dialer.DualStack (IPv6 "Happy Eyeballs") support is
	// enabled, this may be called multiple times.
	ConnectStart func(network, addr string)

	// ConnectDone is called when a new connection's Dial
	// completes. The provided err indicates whether the
	// connection completedly successfully.
	// If net.Dialer.DualStack ("Happy Eyeballs") support is
	// enabled, this may be called multiple times.
	ConnectDone func(network, addr string, err error)

	// TLSHandshakeStart is called when the TLS handshake is started. When
	// connecting to an HTTPS site via an HTTP proxy, the handshake happens
	// after the CONNECT request is processed by the proxy.
	TLSHandshakeStart func()

	// TLSHandshakeDone is called after the TLS handshake with either the
	// successful handshake's connection state, or a non-nil error on handshake
	// failure.
	TLSHandshakeDone func(tls.ConnectionState, error)

	// WroteHeaderField is called after the Transport has written
	// each request header. At the time of this call the value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment