Package http

Overview ▾

Package http provides HTTP client and server implementations.

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

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

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

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

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

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

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

req, err := http.NewRequest("GET", "http://example.com", nil)
// ...
req.Header.Add("If-None-Match", `W/"wyzzy"`)
resp, err := client.Do(req)
// ...

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

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

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

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 ▾

Constants
Variables
func CanonicalHeaderKey(s string) string
func DetectContentType(data []byte) string
func Error(w ResponseWriter, error string, code int)
func Get(url string) (resp *Response, err error)
func Handle(pattern string, handler Handler)
func HandleFunc(pattern string, handler func(ResponseWriter, *Request))
func Head(url string) (resp *Response, err error)
func ListenAndServe(addr string, handler Handler) error
func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error
func MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser
func NewRequest(method, url string, body io.Reader) (*Request, error)
func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error)
func NotFound(w ResponseWriter, r *Request)
func ParseHTTPVersion(vers string) (major, minor int, ok bool)
func ParseTime(text string) (t time.Time, err error)
func Post(url, contentType string, body io.Reader) (resp *Response, err error)
func PostForm(url string, data url.Values) (resp *Response, err error)
func ProxyFromEnvironment(req *Request) (*url.URL, error)
func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error)
func ReadRequest(b *bufio.Reader) (*Request, error)
func ReadResponse(r *bufio.Reader, req *Request) (*Response, error)
func Redirect(w ResponseWriter, r *Request, url string, code int)
func Serve(l net.Listener, handler Handler) error
func ServeContent(w ResponseWriter, req *Request, name string, modtime time.Time, content io.ReadSeeker)
func ServeFile(w ResponseWriter, r *Request, name string)
func ServeTLS(l net.Listener, handler Handler, certFile, keyFile string) error
func SetCookie(w ResponseWriter, cookie *Cookie)
func StatusText(code int) string
func alwaysFalse() bool
func appendTime(b []byte, t time.Time) []byte
func basicAuth(username, password string) string
func bodyAllowedForStatus(status int) bool
func bufioWriterPool(size int) *sync.Pool
func canonicalAddr(url *url.URL) string
func checkPreconditions(w ResponseWriter, r *Request, modtime time.Time) (done bool, rangeHeader string)
func checkWriteHeaderCode(code int)
func chunked(te []string) bool
func cleanHost(in string) string
func cleanPath(p string) string
func cloneMultipartFileHeader(fh *multipart.FileHeader) *multipart.FileHeader
func cloneMultipartForm(f *multipart.Form) *multipart.Form
func cloneTLSConfig(cfg *tls.Config) *tls.Config
func cloneURL(u *url.URL) *url.URL
func cloneURLValues(v url.Values) url.Values
func containsDotDot(v string) bool
func copyValues(dst, src url.Values)
func defaultCheckRedirect(req *Request, via []*Request) error
func dirList(w ResponseWriter, r *Request, f File)
func envProxyFunc() func(*url.URL) (*url.URL, error)
func etagStrongMatch(a, b string) bool
func etagWeakMatch(a, b string) bool
func fixLength(isResponse bool, status int, requestMethod string, header Header, te []string) (int64, error)
func fixPragmaCacheControl(header Header)
func fixTrailer(header Header, te []string) (Header, error)
func foreachHeaderElement(v string, fn func(string))
func hasPort(s string) bool
func hasToken(v, token string) bool
func hexEscapeNonASCII(s string) string
func htmlEscape(s string) string
func http1ServerSupportsRequest(req *Request) bool
func http2ConfigureServer(s *Server, conf *http2Server) error
func http2ConfigureTransport(t1 *Transport) error
func http2ReadFrameHeader(r io.Reader) (http2FrameHeader, error)
func http2actualContentLength(req *Request) int64
func http2authorityAddr(scheme string, authority string) (addr string)
func http2awaitRequestCancel(req *Request, done <-chan struct{}) error
func http2bodyAllowedForStatus(status int) bool
func http2buildCommonHeaderMaps()
func http2buildCommonHeaderMapsOnce()
func http2canRetryError(err error) bool
func http2checkConnHeaders(req *Request) error
func http2checkPriority(streamID uint32, p http2PriorityParam) error
func http2checkValidHTTP2RequestHeaders(h Header) error
func http2checkWriteHeaderCode(code int)
func http2commaSeparatedTrailers(req *Request) (string, error)
func http2configureTransport(t1 *Transport) (*http2Transport, error)
func http2curGoroutineID() uint64
func http2cutoff64(base int) uint64
func http2encKV(enc *hpack.Encoder, k, v string)
func http2encodeHeaders(enc *hpack.Encoder, h Header, keys []string)
func http2errno(v error) uintptr
func http2foreachHeaderElement(v string, fn func(string))
func http2getDataBufferChunk(size int64) []byte
func http2h1ServerKeepAlivesDisabled(hs *Server) bool
func http2handleHeaderListTooLong(w ResponseWriter, r *Request)
func http2httpCodeString(code int) string
func http2isBadCipher(cipher uint16) bool
func http2isClosedConnError(err error) bool
func http2isConnectionCloseRequest(req *Request) bool
func http2isEOFOrNetReadError(err error) bool
func http2isNoCachedConnError(err error) bool
func http2lowerHeader(v string) string
func http2mustUint31(v int32) uint32
func http2parseContinuationFrame(_ *http2frameCache, fh http2FrameHeader, p []byte) (http2Frame, error)
func http2parseDataFrame(fc *http2frameCache, fh http2FrameHeader, payload []byte) (http2Frame, error)
func http2parseGoAwayFrame(_ *http2frameCache, fh http2FrameHeader, p []byte) (http2Frame, error)
func http2parseHeadersFrame(_ *http2frameCache, fh http2FrameHeader, p []byte) (_ http2Frame, err error)
func http2parsePingFrame(_ *http2frameCache, fh http2FrameHeader, payload []byte) (http2Frame, error)
func http2parsePriorityFrame(_ *http2frameCache, fh http2FrameHeader, payload []byte) (http2Frame, error)
func http2parsePushPromise(_ *http2frameCache, fh http2FrameHeader, p []byte) (_ http2Frame, err error)
func http2parseRSTStreamFrame(_ *http2frameCache, fh http2FrameHeader, p []byte) (http2Frame, error)
func http2parseSettingsFrame(_ *http2frameCache, fh http2FrameHeader, p []byte) (http2Frame, error)
func http2parseUintBytes(s []byte, base int, bitSize int) (n uint64, err error)
func http2parseUnknownFrame(_ *http2frameCache, fh http2FrameHeader, p []byte) (http2Frame, error)
func http2parseWindowUpdateFrame(_ *http2frameCache, fh http2FrameHeader, p []byte) (http2Frame, error)
func http2putDataBufferChunk(p []byte)
func http2readByte(p []byte) (remain []byte, b byte, err error)
func http2readFrameHeader(buf []byte, r io.Reader) (http2FrameHeader, error)
func http2readUint32(p []byte) (remain []byte, v uint32, err error)
func http2registerHTTPSProtocol(t *Transport, rt http2noDialH2RoundTripper) (err error)
func http2serverConnBaseContext(c net.Conn, opts *http2ServeConnOpts) (ctx context.Context, cancel func())
func http2shouldRetryRequest(req *Request, err error, afterBodyWrite bool) (*Request, error)
func http2shouldSendReqContentLength(method string, contentLength int64) bool
func http2splitHeaderBlock(ctx http2writeContext, headerBlock []byte, fn func(ctx http2writeContext, frag []byte, firstFrag, lastFrag bool) error) error
func http2strSliceContains(ss []string, s string) bool
func http2summarizeFrame(f http2Frame) string
func http2terminalReadFrameError(err error) bool
func http2traceFirstResponseByte(trace *httptrace.ClientTrace)
func http2traceGetConn(req *Request, hostPort string)
func http2traceGot100Continue(trace *httptrace.ClientTrace)
func http2traceGot1xxResponseFunc(trace *httptrace.ClientTrace) func(int, textproto.MIMEHeader) error
func http2traceGotConn(req *Request, cc *http2ClientConn, reused bool)
func http2traceHasWroteHeaderField(trace *httptrace.ClientTrace) bool
func http2traceWait100Continue(trace *httptrace.ClientTrace)
func http2traceWroteHeaderField(trace *httptrace.ClientTrace, k, v string)
func http2traceWroteHeaders(trace *httptrace.ClientTrace)
func http2traceWroteRequest(trace *httptrace.ClientTrace, err error)
func http2validPseudoPath(v string) bool
func http2validStreamID(streamID uint32) bool
func http2validStreamIDOrZero(streamID uint32) bool
func http2validWireHeaderFieldName(v string) bool
func http2writeEndsStream(w http2writeFramer) bool
func idnaASCII(v string) (string, error)
func init()
func is408Message(buf []byte) bool
func isASCII(s string) bool
func isCommonNetReadError(err error) bool
func isCookieDomainName(s string) bool
func isCookieNameValid(raw string) bool
func isDomainOrSubdomain(sub, parent string) bool
func isIdentity(te []string) bool
func isKnownInMemoryReader(r io.Reader) bool
func isNotToken(r rune) bool
func isSlashRune(r rune) bool
func isTT(b byte) bool
func isTokenBoundary(b byte) bool
func isUnsupportedTEError(err error) bool
func isWS(b byte) bool
func isZeroTime(t time.Time) bool
func knownRoundTripperImpl(rt RoundTripper, req *Request) bool
func localRedirect(w ResponseWriter, r *Request, newPath string)
func logf(r *Request, format string, args ...interface{})
func mapDirOpenError(originalErr error, name string) error
func mergeSetHeader(dst *Header, src Header)
func newBufioReader(r io.Reader) *bufio.Reader
func newBufioWriterSize(w io.Writer, size int) *bufio.Writer
func newLoggingConn(baseName string, c net.Conn) net.Conn
func newReadWriteCloserBody(br *bufio.Reader, rwc io.ReadWriteCloser) io.ReadWriteCloser
func newTextprotoReader(br *bufio.Reader) *textproto.Reader
func newTransferWriter(r interface{}) (t *transferWriter, err error)
func noResponseBodyExpected(requestMethod string) bool
func nop()
func numLeadingCRorLF(v []byte) (n int)
func parseBasicAuth(auth string) (username, password string, ok bool)
func parseContentLength(cl string) (int64, error)
func parseCookieValue(raw string, allowDoubleQuote bool) (string, bool)
func parsePostForm(r *Request) (vs url.Values, err error)
func parseRange(s string, size int64) ([]httpRange, error)
func parseRequestLine(line string) (method, requestURI, proto string, ok bool)
func putBufioReader(br *bufio.Reader)
func putBufioWriter(bw *bufio.Writer)
func putTextprotoReader(r *textproto.Reader)
func rangesMIMESize(ranges []httpRange, contentType string, contentSize int64) (encSize int64)
func readRequest(b *bufio.Reader, deleteHostHeader bool) (req *Request, err error)
func readTransfer(msg interface{}, r *bufio.Reader) (err error)
func redirectBehavior(reqMethod string, resp *Response, ireq *Request) (redirectMethod string, shouldRedirect, includeBody bool)
func refererForURL(lastReq, newReq *url.URL) string
func registerOnHitEOF(rc io.ReadCloser, fn func())
func relevantCaller() runtime.Frame
func removeEmptyPort(host string) string
func removeZone(host string) string
func requestBodyRemains(rc io.ReadCloser) bool
func requestMethodUsuallyLacksBody(method string) bool
func resetProxyConfig()
func sanitizeCookieName(n string) string
func sanitizeCookiePath(v string) string
func sanitizeCookieValue(v string) string
func sanitizeOrWarn(fieldName string, valid func(byte) bool, v string) string
func scanETag(s string) (etag string, remain string)
func seeUpcomingDoubleCRLF(r *bufio.Reader) bool
func send(ireq *Request, rt RoundTripper, deadline time.Time) (resp *Response, didTimeout func() bool, err error)
func serveContent(w ResponseWriter, r *Request, name string, modtime time.Time, sizeFunc func() (int64, error), content io.ReadSeeker)
func serveFile(w ResponseWriter, r *Request, fs FileSystem, name string, redirect bool)
func setLastModified(w ResponseWriter, modtime time.Time)
func setRequestCancel(req *Request, rt RoundTripper, deadline time.Time) (stopTimer func(), didTimeout func() bool)
func shouldClose(major, minor int, header Header, removeCloseHeader bool) bool
func shouldCopyHeaderOnRedirect(headerKey string, initial, dest *url.URL) bool
func sockssplitHostPort(address string) (string, int, error)
func srcIsRegularFile(src io.Reader) (isRegular bool, err error)
func strSliceContains(ss []string, s string) bool
func stringContainsCTLByte(s string) bool
func stripHostPort(h string) string
func stripPassword(u *url.URL) string
func sumRangesSize(ranges []httpRange) (size int64)
func suppressedHeaders(status int) []string
func timeBeforeContextDeadline(t time.Time, ctx context.Context) bool
func tlsRecordHeaderLooksLikeHTTP(hdr [5]byte) bool
func toHTTPError(err error) (msg string, httpStatus int)
func urlErrorOp(method string) string
func validCookieDomain(v string) bool
func validCookieExpires(t time.Time) bool
func validCookiePathByte(b byte) bool
func validCookieValueByte(b byte) bool
func validMethod(method string) bool
func validNextProto(proto string) bool
func valueOrDefault(value, def string) string
func writeNotModified(w ResponseWriter)
func writeStatusLine(bw *bufio.Writer, is11 bool, code int, scratch []byte)
type Client
    func (c *Client) CloseIdleConnections()
    func (c *Client) Do(req *Request) (*Response, error)
    func (c *Client) Get(url string) (resp *Response, err error)
    func (c *Client) Head(url string) (resp *Response, err error)
    func (c *Client) Post(url, contentType string, body io.Reader) (resp *Response, err error)
    func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error)
    func (c *Client) checkRedirect(req *Request, via []*Request) error
    func (c *Client) deadline() time.Time
    func (c *Client) do(req *Request) (retres *Response, reterr error)
    func (c *Client) makeHeadersCopier(ireq *Request) func(*Request)
    func (c *Client) send(req *Request, deadline time.Time) (resp *Response, didTimeout func() bool, err error)
    func (c *Client) transport() RoundTripper
type CloseNotifier
type ConnState
    func (c ConnState) String() string
type Cookie
    func readCookies(h Header, filter string) []*Cookie
    func readSetCookies(h Header) []*Cookie
    func (c *Cookie) String() string
type CookieJar
type Dir
    func (d Dir) Open(name string) (File, error)
type File
type FileSystem
type Flusher
type Handler
    func FileServer(root FileSystem) Handler
    func NotFoundHandler() Handler
    func RedirectHandler(url string, code int) Handler
    func StripPrefix(prefix string, h Handler) Handler
    func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler
type HandlerFunc
    func http2new400Handler(err error) HandlerFunc
    func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request)
type Header
    func cloneOrMakeHeader(hdr Header) Header
    func http2cloneHeader(h Header) Header
    func (h Header) Add(key, value string)
    func (h Header) Clone() Header
    func (h Header) Del(key string)
    func (h Header) Get(key string) string
    func (h Header) Set(key, value string)
    func (h Header) Values(key string) []string
    func (h Header) Write(w io.Writer) error
    func (h Header) WriteSubset(w io.Writer, exclude map[string]bool) error
    func (h Header) get(key string) string
    func (h Header) has(key string) bool
    func (h Header) sortedKeyValues(exclude map[string]bool) (kvs []keyValues, hs *headerSorter)
    func (h Header) write(w io.Writer, trace *httptrace.ClientTrace) error
    func (h Header) writeSubset(w io.Writer, exclude map[string]bool, trace *httptrace.ClientTrace) error
type Hijacker
type ProtocolError
    func (pe *ProtocolError) Error() string
type PushOptions
type Pusher
type Request
    func (r *Request) AddCookie(c *Cookie)
    func (r *Request) BasicAuth() (username, password string, ok bool)
    func (r *Request) Clone(ctx context.Context) *Request
    func (r *Request) Context() context.Context
    func (r *Request) Cookie(name string) (*Cookie, error)
    func (r *Request) Cookies() []*Cookie
    func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error)
    func (r *Request) FormValue(key string) string
    func (r *Request) MultipartReader() (*multipart.Reader, error)
    func (r *Request) ParseForm() error
    func (r *Request) ParseMultipartForm(maxMemory int64) error
    func (r *Request) PostFormValue(key string) string
    func (r *Request) ProtoAtLeast(major, minor int) bool
    func (r *Request) Referer() string
    func (r *Request) SetBasicAuth(username, password string)
    func (r *Request) UserAgent() string
    func (r *Request) WithContext(ctx context.Context) *Request
    func (r *Request) Write(w io.Writer) error
    func (r *Request) WriteProxy(w io.Writer) error
    func (r *Request) closeBody()
    func (r *Request) expectsContinue() bool
    func (r *Request) isH2Upgrade() bool
    func (r *Request) isReplayable() bool
    func (r *Request) multipartReader(allowMixed bool) (*multipart.Reader, error)
    func (r *Request) outgoingLength() int64
    func (r *Request) requiresHTTP1() bool
    func (r *Request) wantsClose() bool
    func (r *Request) wantsHttp10KeepAlive() bool
    func (r *Request) write(w io.Writer, usingProxy bool, extraHeaders Header, waitForContinue func() bool) (err error)
type Response
    func (r *Response) Cookies() []*Cookie
    func (r *Response) Location() (*url.URL, error)
    func (r *Response) ProtoAtLeast(major, minor int) bool
    func (r *Response) Write(w io.Writer) error
    func (r *Response) bodyIsWritable() bool
    func (r *Response) closeBody()
    func (r *Response) isProtocolSwitch() bool
type ResponseWriter
type RoundTripper
    func NewFileTransport(fs FileSystem) RoundTripper
type SameSite
type ServeMux
    func NewServeMux() *ServeMux
    func (mux *ServeMux) Handle(pattern string, handler Handler)
    func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))
    func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string)
    func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request)
    func (mux *ServeMux) handler(host, path string) (h Handler, pattern string)
    func (mux *ServeMux) match(path string) (h Handler, pattern string)
    func (mux *ServeMux) redirectToPathSlash(host, path string, u *url.URL) (*url.URL, bool)
    func (mux *ServeMux) shouldRedirectRLocked(host, path string) bool
type Server
    func (srv *Server) Close() error
    func (srv *Server) ListenAndServe() error
    func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error
    func (srv *Server) RegisterOnShutdown(f func())
    func (srv *Server) Serve(l net.Listener) error
    func (srv *Server) ServeTLS(l net.Listener, certFile, keyFile string) error
    func (srv *Server) SetKeepAlivesEnabled(v bool)
    func (srv *Server) Shutdown(ctx context.Context) error
    func (s *Server) closeDoneChanLocked()
    func (s *Server) closeIdleConns() bool
    func (s *Server) closeListenersLocked() error
    func (s *Server) doKeepAlives() bool
    func (s *Server) getDoneChan() <-chan struct{}
    func (s *Server) getDoneChanLocked() chan struct{}
    func (s *Server) idleTimeout() time.Duration
    func (srv *Server) initialReadLimitSize() int64
    func (s *Server) logf(format string, args ...interface{})
    func (srv *Server) maxHeaderBytes() int
    func (srv *Server) newConn(rwc net.Conn) *conn
    func (srv *Server) onceSetNextProtoDefaults()
    func (srv *Server) onceSetNextProtoDefaults_Serve()
    func (s *Server) readHeaderTimeout() time.Duration
    func (srv *Server) setupHTTP2_Serve() error
    func (srv *Server) setupHTTP2_ServeTLS() error
    func (srv *Server) shouldConfigureHTTP2ForServe() bool
    func (s *Server) shuttingDown() bool
    func (s *Server) trackConn(c *conn, add bool)
    func (s *Server) trackListener(ln *net.Listener, add bool) bool
type Transport
    func (t *Transport) CancelRequest(req *Request)
    func (t *Transport) Clone() *Transport
    func (t *Transport) CloseIdleConnections()
    func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper)
    func (t *Transport) RoundTrip(req *Request) (*Response, error)
    func (t *Transport) alternateRoundTripper(req *Request) RoundTripper
    func (t *Transport) cancelRequest(req *Request, err error)
    func (t *Transport) connectMethodForRequest(treq *transportRequest) (cm connectMethod, err error)
    func (t *Transport) customDialTLS(ctx context.Context, network, addr string) (conn net.Conn, err error)
    func (t *Transport) decConnsPerHost(key connectMethodKey)
    func (t *Transport) dial(ctx context.Context, network, addr string) (net.Conn, error)
    func (t *Transport) dialConn(ctx context.Context, cm connectMethod) (pconn *persistConn, err error)
    func (t *Transport) dialConnFor(w *wantConn)
    func (t *Transport) getConn(treq *transportRequest, cm connectMethod) (pc *persistConn, err error)
    func (t *Transport) hasCustomTLSDialer() bool
    func (t *Transport) maxIdleConnsPerHost() int
    func (t *Transport) onceSetNextProtoDefaults()
    func (t *Transport) putOrCloseIdleConn(pconn *persistConn)
    func (t *Transport) queueForDial(w *wantConn)
    func (t *Transport) queueForIdleConn(w *wantConn) (delivered bool)
    func (t *Transport) readBufferSize() int
    func (t *Transport) removeIdleConn(pconn *persistConn) bool
    func (t *Transport) removeIdleConnLocked(pconn *persistConn) bool
    func (t *Transport) replaceReqCanceler(r *Request, fn func(error)) bool
    func (t *Transport) roundTrip(req *Request) (*Response, error)
    func (t *Transport) setReqCanceler(r *Request, fn func(error))
    func (t *Transport) tryPutIdleConn(pconn *persistConn) error
    func (t *Transport) useRegisteredProtocol(req *Request) bool
    func (t *Transport) writeBufferSize() int
type atomicBool
    func (b *atomicBool) isSet() bool
    func (b *atomicBool) setTrue()
type badRequestError
    func (e badRequestError) Error() string
type badStringError
    func (e *badStringError) Error() string
type body
    func (b *body) Close() error
    func (b *body) Read(p []byte) (n int, err error)
    func (b *body) bodyRemains() bool
    func (b *body) didEarlyClose() bool
    func (b *body) readLocked(p []byte) (n int, err error)
    func (b *body) readTrailer() error
    func (b *body) registerOnHitEOF(fn func())
    func (b *body) unreadDataSizeLocked() int64
type bodyEOFSignal
    func (es *bodyEOFSignal) Close() error
    func (es *bodyEOFSignal) Read(p []byte) (n int, err error)
    func (es *bodyEOFSignal) condfn(err error) error
type bodyLocked
    func (bl bodyLocked) Read(p []byte) (n int, err error)
type bufioFlushWriter
    func (fw bufioFlushWriter) Write(p []byte) (n int, err error)
type byteReader
    func (br *byteReader) Read(p []byte) (n int, err error)
type cancelTimerBody
    func (b *cancelTimerBody) Close() error
    func (b *cancelTimerBody) Read(p []byte) (n int, err error)
type checkConnErrorWriter
    func (w checkConnErrorWriter) Write(p []byte) (n int, err error)
type chunkWriter
    func (cw *chunkWriter) Write(p []byte) (n int, err error)
    func (cw *chunkWriter) close()
    func (cw *chunkWriter) flush()
    func (cw *chunkWriter) writeHeader(p []byte)
type closeWriter
type condResult
    func checkIfMatch(w ResponseWriter, r *Request) condResult
    func checkIfModifiedSince(r *Request, modtime time.Time) condResult
    func checkIfNoneMatch(w ResponseWriter, r *Request) condResult
    func checkIfRange(w ResponseWriter, r *Request, modtime time.Time) condResult
    func checkIfUnmodifiedSince(r *Request, modtime time.Time) condResult
type conn
    func (c *conn) close()
    func (c *conn) closeWriteAndWait()
    func (c *conn) finalFlush()
    func (c *conn) getState() (state ConnState, unixSec int64)
    func (c *conn) hijackLocked() (rwc net.Conn, buf *bufio.ReadWriter, err error)
    func (c *conn) hijacked() bool
    func (c *conn) readRequest(ctx context.Context) (w *response, err error)
    func (c *conn) serve(ctx context.Context)
    func (c *conn) setState(nc net.Conn, state ConnState)
type connLRU
    func (cl *connLRU) add(pc *persistConn)
    func (cl *connLRU) len() int
    func (cl *connLRU) remove(pc *persistConn)
    func (cl *connLRU) removeOldest() *persistConn
type connReader
    func (cr *connReader) Read(p []byte) (n int, err error)
    func (cr *connReader) abortPendingRead()
    func (cr *connReader) backgroundRead()
    func (cr *connReader) closeNotify()
    func (cr *connReader) handleReadError(_ error)
    func (cr *connReader) hitReadLimit() bool
    func (cr *connReader) lock()
    func (cr *connReader) setInfiniteReadLimit()
    func (cr *connReader) setReadLimit(remain int64)
    func (cr *connReader) startBackgroundRead()
    func (cr *connReader) unlock()
type connectMethod
    func (cm *connectMethod) addr() string
    func (cm *connectMethod) key() connectMethodKey
    func (cm *connectMethod) proxyAuth() string
    func (cm *connectMethod) scheme() string
    func (cm *connectMethod) tlsHost() string
type connectMethodKey
    func (k connectMethodKey) String() string
type contextKey
    func (k *contextKey) String() string
type countingWriter
    func (w *countingWriter) Write(p []byte) (n int, err error)
type errorReader
    func (r errorReader) Read(p []byte) (n int, err error)
type exactSig
    func (e *exactSig) match(data []byte, firstNonWS int) string
type expectContinueReader
    func (ecr *expectContinueReader) Close() error
    func (ecr *expectContinueReader) Read(p []byte) (n int, err error)
type extraHeader
    func (h extraHeader) Write(w *bufio.Writer)
type fakeLocker
    func (fakeLocker) Lock()
    func (fakeLocker) Unlock()
type fileHandler
    func (f *fileHandler) ServeHTTP(w ResponseWriter, r *Request)
type fileTransport
    func (t fileTransport) RoundTrip(req *Request) (resp *Response, err error)
type finishAsyncByteRead
    func (fr finishAsyncByteRead) Read(p []byte) (n int, err error)
type globalOptionsHandler
    func (globalOptionsHandler) ServeHTTP(w ResponseWriter, r *Request)
type gzipReader
    func (gz *gzipReader) Close() error
    func (gz *gzipReader) Read(p []byte) (n int, err error)
type h2Transport
type headerSorter
    func (s *headerSorter) Len() int
    func (s *headerSorter) Less(i, j int) bool
    func (s *headerSorter) Swap(i, j int)
type htmlSig
    func (h htmlSig) match(data []byte, firstNonWS int) string
type http2ClientConn
    func http2filterOutClientConn(in []*http2ClientConn, exclude *http2ClientConn) []*http2ClientConn
    func (cc *http2ClientConn) CanTakeNewRequest() bool
    func (cc *http2ClientConn) Close() error
    func (cc *http2ClientConn) Ping(ctx context.Context) error
    func (cc *http2ClientConn) RoundTrip(req *Request) (*Response, error)
    func (cc *http2ClientConn) Shutdown(ctx context.Context) error
    func (cc *http2ClientConn) awaitOpenSlotForRequest(req *Request) error
    func (cc *http2ClientConn) canTakeNewRequestLocked() bool
    func (cc *http2ClientConn) closeIfIdle()
    func (cc *http2ClientConn) encodeHeaders(req *Request, addGzipHeader bool, trailers string, contentLength int64) ([]byte, error)
    func (cc *http2ClientConn) encodeTrailers(req *Request) ([]byte, error)
    func (cc *http2ClientConn) forgetStreamID(id uint32)
    func (cc *http2ClientConn) frameScratchBuffer() []byte
    func (cc *http2ClientConn) idleState() http2clientConnIdleState
    func (cc *http2ClientConn) idleStateLocked() (st http2clientConnIdleState)
    func (cc *http2ClientConn) logf(format string, args ...interface{})
    func (cc *http2ClientConn) newStream() *http2clientStream
    func (cc *http2ClientConn) onIdleTimeout()
    func (cc *http2ClientConn) putFrameScratchBuffer(buf []byte)
    func (cc *http2ClientConn) readLoop()
    func (cc *http2ClientConn) responseHeaderTimeout() time.Duration
    func (cc *http2ClientConn) roundTrip(req *Request) (res *Response, gotErrAfterReqBodyWrite bool, err error)
    func (cc *http2ClientConn) sendGoAway() error
    func (cc *http2ClientConn) setGoAway(f *http2GoAwayFrame)
    func (cc *http2ClientConn) streamByID(id uint32, andRemove bool) *http2clientStream
    func (cc *http2ClientConn) tooIdleLocked() bool
    func (cc *http2ClientConn) vlogf(format string, args ...interface{})
    func (cc *http2ClientConn) writeHeader(name, value string)
    func (cc *http2ClientConn) writeHeaders(streamID uint32, endStream bool, maxFrameSize int, hdrs []byte) error
    func (cc *http2ClientConn) writeStreamReset(streamID uint32, code http2ErrCode, err error)
type http2ClientConnPool
type http2ConnectionError
    func (e http2ConnectionError) Error() string
type http2ContinuationFrame
    func (h http2ContinuationFrame) Header() http2FrameHeader
    func (f *http2ContinuationFrame) HeaderBlockFragment() []byte
    func (f *http2ContinuationFrame) HeadersEnded() bool
    func (h http2ContinuationFrame) String() string
    func (h *http2ContinuationFrame) checkValid()
    func (h *http2ContinuationFrame) invalidate()
    func (h http2ContinuationFrame) writeDebug(buf *bytes.Buffer)
type http2DataFrame
    func (f *http2DataFrame) Data() []byte
    func (h http2DataFrame) Header() http2FrameHeader
    func (f *http2DataFrame) StreamEnded() bool
    func (h http2DataFrame) String() string
    func (h *http2DataFrame) checkValid()
    func (h *http2DataFrame) invalidate()
    func (h http2DataFrame) writeDebug(buf *bytes.Buffer)
type http2ErrCode
    func (e http2ErrCode) String() string
type http2Flags
    func (f http2Flags) Has(v http2Flags) bool
type http2Frame
type http2FrameHeader
    func (h http2FrameHeader) Header() http2FrameHeader
    func (h http2FrameHeader) String() string
    func (h *http2FrameHeader) checkValid()
    func (h *http2FrameHeader) invalidate()
    func (h http2FrameHeader) writeDebug(buf *bytes.Buffer)
type http2FrameType
    func (t http2FrameType) String() string
type http2FrameWriteRequest
    func (wr http2FrameWriteRequest) Consume(n int32) (http2FrameWriteRequest, http2FrameWriteRequest, int)
    func (wr http2FrameWriteRequest) DataSize() int
    func (wr http2FrameWriteRequest) StreamID() uint32
    func (wr http2FrameWriteRequest) String() string
    func (wr http2FrameWriteRequest) isControl() bool
    func (wr *http2FrameWriteRequest) replyToWriter(err error)
type http2Framer
    func http2NewFramer(w io.Writer, r io.Reader) *http2Framer
    func (fr *http2Framer) ErrorDetail() error
    func (fr *http2Framer) ReadFrame() (http2Frame, error)
    func (fr *http2Framer) SetMaxReadFrameSize(v uint32)
    func (fr *http2Framer) SetReuseFrames()
    func (f *http2Framer) WriteContinuation(streamID uint32, endHeaders bool, headerBlockFragment []byte) error
    func (f *http2Framer) WriteData(streamID uint32, endStream bool, data []byte) error
    func (f *http2Framer) WriteDataPadded(streamID uint32, endStream bool, data, pad []byte) error
    func (f *http2Framer) WriteGoAway(maxStreamID uint32, code http2ErrCode, debugData []byte) error
    func (f *http2Framer) WriteHeaders(p http2HeadersFrameParam) error
    func (f *http2Framer) WritePing(ack bool, data [8]byte) error
    func (f *http2Framer) WritePriority(streamID uint32, p http2PriorityParam) error
    func (f *http2Framer) WritePushPromise(p http2PushPromiseParam) error
    func (f *http2Framer) WriteRSTStream(streamID uint32, code http2ErrCode) error
    func (f *http2Framer) WriteRawFrame(t http2FrameType, flags http2Flags, streamID uint32, payload []byte) error
    func (f *http2Framer) WriteSettings(settings ...http2Setting) error
    func (f *http2Framer) WriteSettingsAck() error
    func (f *http2Framer) WriteWindowUpdate(streamID, incr uint32) error
    func (fr *http2Framer) checkFrameOrder(f http2Frame) error
    func (fr *http2Framer) connError(code http2ErrCode, reason string) error
    func (f *http2Framer) endWrite() error
    func (f *http2Framer) logWrite()
    func (fr *http2Framer) maxHeaderListSize() uint32
    func (fr *http2Framer) maxHeaderStringLen() int
    func (fr *http2Framer) readMetaFrame(hf *http2HeadersFrame) (*http2MetaHeadersFrame, error)
    func (f *http2Framer) startWrite(ftype http2FrameType, flags http2Flags, streamID uint32)
    func (f *http2Framer) writeByte(v byte)
    func (f *http2Framer) writeBytes(v []byte)
    func (f *http2Framer) writeUint16(v uint16)
    func (f *http2Framer) writeUint32(v uint32)
type http2GoAwayError
    func (e http2GoAwayError) Error() string
type http2GoAwayFrame
    func (f *http2GoAwayFrame) DebugData() []byte
    func (h http2GoAwayFrame) Header() http2FrameHeader
    func (h http2GoAwayFrame) String() string
    func (h *http2GoAwayFrame) checkValid()
    func (h *http2GoAwayFrame) invalidate()
    func (h http2GoAwayFrame) writeDebug(buf *bytes.Buffer)
type http2HeadersFrame
    func (f *http2HeadersFrame) HasPriority() bool
    func (h http2HeadersFrame) Header() http2FrameHeader
    func (f *http2HeadersFrame) HeaderBlockFragment() []byte
    func (f *http2HeadersFrame) HeadersEnded() bool
    func (f *http2HeadersFrame) StreamEnded() bool
    func (h http2HeadersFrame) String() string
    func (h *http2HeadersFrame) checkValid()
    func (h *http2HeadersFrame) invalidate()
    func (h http2HeadersFrame) writeDebug(buf *bytes.Buffer)
type http2HeadersFrameParam
type http2MetaHeadersFrame
    func (f http2MetaHeadersFrame) HasPriority() bool
    func (h http2MetaHeadersFrame) Header() http2FrameHeader
    func (f http2MetaHeadersFrame) HeaderBlockFragment() []byte
    func (f http2MetaHeadersFrame) HeadersEnded() bool
    func (mh *http2MetaHeadersFrame) PseudoFields() []hpack.HeaderField
    func (mh *http2MetaHeadersFrame) PseudoValue(pseudo string) string
    func (mh *http2MetaHeadersFrame) RegularFields() []hpack.HeaderField
    func (f http2MetaHeadersFrame) StreamEnded() bool
    func (h http2MetaHeadersFrame) String() string
    func (mh *http2MetaHeadersFrame) checkPseudos() error
    func (h http2MetaHeadersFrame) checkValid()
    func (h http2MetaHeadersFrame) invalidate()
    func (h http2MetaHeadersFrame) writeDebug(buf *bytes.Buffer)
type http2OpenStreamOptions
type http2PingFrame
    func (h http2PingFrame) Header() http2FrameHeader
    func (f *http2PingFrame) IsAck() bool
    func (h http2PingFrame) String() string
    func (h *http2PingFrame) checkValid()
    func (h *http2PingFrame) invalidate()
    func (h http2PingFrame) writeDebug(buf *bytes.Buffer)
type http2PriorityFrame
    func (h http2PriorityFrame) Header() http2FrameHeader
    func (p http2PriorityFrame) IsZero() bool
    func (h http2PriorityFrame) String() string
    func (h *http2PriorityFrame) checkValid()
    func (h *http2PriorityFrame) invalidate()
    func (h http2PriorityFrame) writeDebug(buf *bytes.Buffer)
type http2PriorityParam
    func (p http2PriorityParam) IsZero() bool
type http2PriorityWriteSchedulerConfig
type http2PushPromiseFrame
    func (h http2PushPromiseFrame) Header() http2FrameHeader
    func (f *http2PushPromiseFrame) HeaderBlockFragment() []byte
    func (f *http2PushPromiseFrame) HeadersEnded() bool
    func (h http2PushPromiseFrame) String() string
    func (h *http2PushPromiseFrame) checkValid()
    func (h *http2PushPromiseFrame) invalidate()
    func (h http2PushPromiseFrame) writeDebug(buf *bytes.Buffer)
type http2PushPromiseParam
type http2RSTStreamFrame
    func (h http2RSTStreamFrame) Header() http2FrameHeader
    func (h http2RSTStreamFrame) String() string
    func (h *http2RSTStreamFrame) checkValid()
    func (h *http2RSTStreamFrame) invalidate()
    func (h http2RSTStreamFrame) writeDebug(buf *bytes.Buffer)
type http2RoundTripOpt
type http2ServeConnOpts
    func (o *http2ServeConnOpts) baseConfig() *Server
    func (o *http2ServeConnOpts) context() context.Context
    func (o *http2ServeConnOpts) handler() Handler
type http2Server
    func (s *http2Server) ServeConn(c net.Conn, opts *http2ServeConnOpts)
    func (s *http2Server) initialConnRecvWindowSize() int32
    func (s *http2Server) initialStreamRecvWindowSize() int32
    func (s *http2Server) maxConcurrentStreams() uint32
    func (s *http2Server) maxQueuedControlFrames() int
    func (s *http2Server) maxReadFrameSize() uint32
type http2Setting
    func (s http2Setting) String() string
    func (s http2Setting) Valid() error
type http2SettingID
    func (s http2SettingID) String() string
type http2SettingsFrame
    func (f *http2SettingsFrame) ForeachSetting(fn func(http2Setting) error) error
    func (f *http2SettingsFrame) HasDuplicates() bool
    func (h http2SettingsFrame) Header() http2FrameHeader
    func (f *http2SettingsFrame) IsAck() bool
    func (f *http2SettingsFrame) NumSettings() int
    func (f *http2SettingsFrame) Setting(i int) http2Setting
    func (h http2SettingsFrame) String() string
    func (f *http2SettingsFrame) Value(id http2SettingID) (v uint32, ok bool)
    func (h *http2SettingsFrame) checkValid()
    func (h *http2SettingsFrame) invalidate()
    func (h http2SettingsFrame) writeDebug(buf *bytes.Buffer)
type http2StreamError
    func http2streamError(id uint32, code http2ErrCode) http2StreamError
    func (e http2StreamError) Error() string
    func (se http2StreamError) staysWithinBuffer(max int) bool
    func (se http2StreamError) writeFrame(ctx http2writeContext) error
type http2Transport
    func (t *http2Transport) CloseIdleConnections()
    func (t *http2Transport) NewClientConn(c net.Conn) (*http2ClientConn, error)
    func (t *http2Transport) RoundTrip(req *Request) (*Response, error)
    func (t *http2Transport) RoundTripOpt(req *Request, opt http2RoundTripOpt) (*Response, error)
    func (t *http2Transport) connPool() http2ClientConnPool
    func (t *http2Transport) dialClientConn(addr string, singleUse bool) (*http2ClientConn, error)
    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) disableCompression() bool
    func (t *http2Transport) disableKeepAlives() bool
    func (t *http2Transport) expectContinueTimeout() time.Duration
    func (t *http2Transport) getBodyWriterState(cs *http2clientStream, body io.Reader) (s http2bodyWriterState)
    func (t *http2Transport) idleConnTimeout() time.Duration
    func (t *http2Transport) initConnPool()
    func (t *http2Transport) logf(format string, args ...interface{})
    func (t *http2Transport) maxHeaderListSize() uint32
    func (t *http2Transport) newClientConn(c net.Conn, singleUse bool) (*http2ClientConn, error)
    func (t *http2Transport) newTLSConfig(host string) *tls.Config
    func (t *http2Transport) vlogf(format string, args ...interface{})
type http2UnknownFrame
    func (h http2UnknownFrame) Header() http2FrameHeader
    func (f *http2UnknownFrame) Payload() []byte
    func (h http2UnknownFrame) String() string
    func (h *http2UnknownFrame) checkValid()
    func (h *http2UnknownFrame) invalidate()
    func (h http2UnknownFrame) writeDebug(buf *bytes.Buffer)
type http2WindowUpdateFrame
    func (h http2WindowUpdateFrame) Header() http2FrameHeader
    func (h http2WindowUpdateFrame) String() string
    func (h *http2WindowUpdateFrame) checkValid()
    func (h *http2WindowUpdateFrame) invalidate()
    func (h http2WindowUpdateFrame) writeDebug(buf *bytes.Buffer)
type http2WriteScheduler
    func http2NewPriorityWriteScheduler(cfg *http2PriorityWriteSchedulerConfig) http2WriteScheduler
    func http2NewRandomWriteScheduler() http2WriteScheduler
type http2addConnCall
    func (c *http2addConnCall) run(t *http2Transport, key string, tc *tls.Conn)
type http2badStringError
    func (e *http2badStringError) Error() string
type http2bodyReadMsg
type http2bodyWriterState
    func (s http2bodyWriterState) cancel()
    func (s http2bodyWriterState) on100()
    func (s http2bodyWriterState) scheduleBodyWrite()
type http2bufferedWriter
    func http2newBufferedWriter(w io.Writer) *http2bufferedWriter
    func (w *http2bufferedWriter) Available() int
    func (w *http2bufferedWriter) Flush() error
    func (w *http2bufferedWriter) Write(p []byte) (n int, err error)
type http2chunkWriter
    func (cw http2chunkWriter) Write(p []byte) (n int, err error)
type http2clientConnIdleState
type http2clientConnPool
    func (p *http2clientConnPool) GetClientConn(req *Request, addr string) (*http2ClientConn, error)
    func (p *http2clientConnPool) MarkDead(cc *http2ClientConn)
    func (p *http2clientConnPool) addConn(key string, cc *http2ClientConn)
    func (p *http2clientConnPool) addConnIfNeeded(key string, t *http2Transport, c *tls.Conn) (used bool, err error)
    func (p *http2clientConnPool) addConnLocked(key string, cc *http2ClientConn)
    func (p *http2clientConnPool) closeIdleConnections()
    func (p *http2clientConnPool) getClientConn(req *Request, addr string, dialOnMiss bool) (*http2ClientConn, error)
    func (p *http2clientConnPool) getStartDialLocked(addr string) *http2dialCall
    func (p *http2clientConnPool) shouldTraceGetConn(st http2clientConnIdleState) bool
type http2clientConnPoolIdleCloser
type http2clientConnReadLoop
    func (rl *http2clientConnReadLoop) cleanup()
    func (rl *http2clientConnReadLoop) endStream(cs *http2clientStream)
    func (rl *http2clientConnReadLoop) endStreamError(cs *http2clientStream, err error)
    func (rl *http2clientConnReadLoop) handleResponse(cs *http2clientStream, f *http2MetaHeadersFrame) (*Response, error)
    func (rl *http2clientConnReadLoop) processData(f *http2DataFrame) error
    func (rl *http2clientConnReadLoop) processGoAway(f *http2GoAwayFrame) error
    func (rl *http2clientConnReadLoop) processHeaders(f *http2MetaHeadersFrame) error
    func (rl *http2clientConnReadLoop) processPing(f *http2PingFrame) error
    func (rl *http2clientConnReadLoop) processPushPromise(f *http2PushPromiseFrame) error
    func (rl *http2clientConnReadLoop) processResetStream(f *http2RSTStreamFrame) error
    func (rl *http2clientConnReadLoop) processSettings(f *http2SettingsFrame) error
    func (rl *http2clientConnReadLoop) processTrailers(cs *http2clientStream, f *http2MetaHeadersFrame) error
    func (rl *http2clientConnReadLoop) processWindowUpdate(f *http2WindowUpdateFrame) error
    func (rl *http2clientConnReadLoop) run() error
type http2clientStream
    func (cs *http2clientStream) abortRequestBodyWrite(err error)
    func (cs *http2clientStream) awaitFlowControl(maxBytes int) (taken int32, err error)
    func (cs *http2clientStream) awaitRequestCancel(req *Request)
    func (cs *http2clientStream) cancelStream()
    func (cs *http2clientStream) checkResetOrDone() error
    func (cs *http2clientStream) copyTrailers()
    func (cs *http2clientStream) get1xxTraceFunc() func(int, textproto.MIMEHeader) error
    func (cs *http2clientStream) getStartedWrite() bool
    func (cs *http2clientStream) writeRequestBody(body io.Reader, bodyCloser io.Closer) (err error)
type http2closeWaiter
    func (cw http2closeWaiter) Close()
    func (cw *http2closeWaiter) Init()
    func (cw http2closeWaiter) Wait()
type http2connError
    func (e http2connError) Error() string
type http2connectionStater
type http2dataBuffer
    func (b *http2dataBuffer) Len() int
    func (b *http2dataBuffer) Read(p []byte) (int, error)
    func (b *http2dataBuffer) Write(p []byte) (int, error)
    func (b *http2dataBuffer) bytesFromFirstChunk() []byte
    func (b *http2dataBuffer) lastChunkOrAlloc(want int64) []byte
type http2dialCall
    func (c *http2dialCall) dial(addr string)
type http2duplicatePseudoHeaderError
    func (e http2duplicatePseudoHeaderError) Error() string
type http2erringRoundTripper
    func (rt http2erringRoundTripper) RoundTrip(*Request) (*Response, error)
type http2errorReader
    func (r http2errorReader) Read(p []byte) (int, error)
type http2flow
    func (f *http2flow) add(n int32) bool
    func (f *http2flow) available() int32
    func (f *http2flow) setConnFlow(cf *http2flow)
    func (f *http2flow) take(n int32)
type http2flushFrameWriter
    func (http2flushFrameWriter) staysWithinBuffer(max int) bool
    func (http2flushFrameWriter) writeFrame(ctx http2writeContext) error
type http2frameCache
    func (fc *http2frameCache) getDataFrame() *http2DataFrame
type http2frameParser
    func http2typeFrameParser(t http2FrameType) http2frameParser
type http2frameWriteResult
type http2gate
    func (g http2gate) Done()
    func (g http2gate) Wait()
type http2goAwayFlowError
    func (http2goAwayFlowError) Error() string
type http2goroutineLock
    func http2newGoroutineLock() http2goroutineLock
    func (g http2goroutineLock) check()
    func (g http2goroutineLock) checkNotOn()
type http2gzipReader
    func (gz *http2gzipReader) Close() error
    func (gz *http2gzipReader) Read(p []byte) (n int, err error)
type http2handlerPanicRST
    func (hp http2handlerPanicRST) staysWithinBuffer(max int) bool
    func (hp http2handlerPanicRST) writeFrame(ctx http2writeContext) error
type http2headerFieldNameError
    func (e http2headerFieldNameError) Error() string
type http2headerFieldValueError
    func (e http2headerFieldValueError) Error() string
type http2headersEnder
type http2headersOrContinuation
type http2httpError
    func (e *http2httpError) Error() string
    func (e *http2httpError) Temporary() bool
    func (e *http2httpError) Timeout() bool
type http2noCachedConnError
    func (http2noCachedConnError) Error() string
    func (http2noCachedConnError) IsHTTP2NoCachedConnError()
type http2noDialClientConnPool
    func (p http2noDialClientConnPool) GetClientConn(req *Request, addr string) (*http2ClientConn, error)
    func (p http2noDialClientConnPool) MarkDead(cc *http2ClientConn)
    func (p http2noDialClientConnPool) addConn(key string, cc *http2ClientConn)
    func (p http2noDialClientConnPool) addConnIfNeeded(key string, t *http2Transport, c *tls.Conn) (used bool, err error)
    func (p http2noDialClientConnPool) addConnLocked(key string, cc *http2ClientConn)
    func (p http2noDialClientConnPool) closeIdleConnections()
    func (p http2noDialClientConnPool) getClientConn(req *Request, addr string, dialOnMiss bool) (*http2ClientConn, error)
    func (p http2noDialClientConnPool) getStartDialLocked(addr string) *http2dialCall
    func (p http2noDialClientConnPool) shouldTraceGetConn(st http2clientConnIdleState) bool
type http2noDialH2RoundTripper
    func (t http2noDialH2RoundTripper) CloseIdleConnections()
    func (t http2noDialH2RoundTripper) NewClientConn(c net.Conn) (*http2ClientConn, error)
    func (rt http2noDialH2RoundTripper) RoundTrip(req *Request) (*Response, error)
    func (t http2noDialH2RoundTripper) RoundTripOpt(req *Request, opt http2RoundTripOpt) (*Response, error)
    func (t http2noDialH2RoundTripper) connPool() http2ClientConnPool
    func (t http2noDialH2RoundTripper) dialClientConn(addr string, singleUse bool) (*http2ClientConn, error)
    func (t http2noDialH2RoundTripper) dialTLS() func(string, string, *tls.Config) (net.Conn, error)
    func (t http2noDialH2RoundTripper) dialTLSDefault(network, addr string, cfg *tls.Config) (net.Conn, error)
    func (t http2noDialH2RoundTripper) disableCompression() bool
    func (t http2noDialH2RoundTripper) disableKeepAlives() bool
    func (t http2noDialH2RoundTripper) expectContinueTimeout() time.Duration
    func (t http2noDialH2RoundTripper) getBodyWriterState(cs *http2clientStream, body io.Reader) (s http2bodyWriterState)
    func (t http2noDialH2RoundTripper) idleConnTimeout() time.Duration
    func (t http2noDialH2RoundTripper) initConnPool()
    func (t http2noDialH2RoundTripper) logf(format string, args ...interface{})
    func (t http2noDialH2RoundTripper) maxHeaderListSize() uint32
    func (t http2noDialH2RoundTripper) newClientConn(c net.Conn, singleUse bool) (*http2ClientConn, error)
    func (t http2noDialH2RoundTripper) newTLSConfig(host string) *tls.Config
    func (t http2noDialH2RoundTripper) vlogf(format string, args ...interface{})
type http2pipe
    func (p *http2pipe) BreakWithError(err error)
    func (p *http2pipe) CloseWithError(err error)
    func (p *http2pipe) Done() <-chan struct{}
    func (p *http2pipe) Err() error
    func (p *http2pipe) Len() int
    func (p *http2pipe) Read(d []byte) (n int, err error)
    func (p *http2pipe) Write(d []byte) (n int, err error)
    func (p *http2pipe) closeDoneLocked()
    func (p *http2pipe) closeWithError(dst *error, err error, fn func())
    func (p *http2pipe) closeWithErrorAndCode(err error, fn func())
type http2pipeBuffer
type http2priorityNode
    func (n *http2priorityNode) addBytes(b int64)
    func (n *http2priorityNode) setParent(parent *http2priorityNode)
    func (n *http2priorityNode) walkReadyInOrder(openParent bool, tmp *[]*http2priorityNode, f func(*http2priorityNode, bool) bool) bool
type http2priorityNodeState
type http2priorityWriteScheduler
    func (ws *http2priorityWriteScheduler) AdjustStream(streamID uint32, priority http2PriorityParam)
    func (ws *http2priorityWriteScheduler) CloseStream(streamID uint32)
    func (ws *http2priorityWriteScheduler) OpenStream(streamID uint32, options http2OpenStreamOptions)
    func (ws *http2priorityWriteScheduler) Pop() (wr http2FrameWriteRequest, ok bool)
    func (ws *http2priorityWriteScheduler) Push(wr http2FrameWriteRequest)
    func (ws *http2priorityWriteScheduler) addClosedOrIdleNode(list *[]*http2priorityNode, maxSize int, n *http2priorityNode)
    func (ws *http2priorityWriteScheduler) removeNode(n *http2priorityNode)
type http2pseudoHeaderError
    func (e http2pseudoHeaderError) Error() string
type http2randomWriteScheduler
    func (ws *http2randomWriteScheduler) AdjustStream(streamID uint32, priority http2PriorityParam)
    func (ws *http2randomWriteScheduler) CloseStream(streamID uint32)
    func (ws *http2randomWriteScheduler) OpenStream(streamID uint32, options http2OpenStreamOptions)
    func (ws *http2randomWriteScheduler) Pop() (http2FrameWriteRequest, bool)
    func (ws *http2randomWriteScheduler) Push(wr http2FrameWriteRequest)
type http2readFrameResult
type http2requestBody
    func (b *http2requestBody) Close() error
    func (b *http2requestBody) Read(p []byte) (n int, err error)
type http2requestParam
type http2resAndError
type http2responseWriter
    func (w *http2responseWriter) CloseNotify() <-chan bool
    func (w *http2responseWriter) Flush()
    func (w *http2responseWriter) Header() Header
    func (w *http2responseWriter) Push(target string, opts *PushOptions) error
    func (w *http2responseWriter) Write(p []byte) (n int, err error)
    func (w *http2responseWriter) WriteHeader(code int)
    func (w *http2responseWriter) WriteString(s string) (n int, err error)
    func (w *http2responseWriter) handlerDone()
    func (w *http2responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error)
type http2responseWriterState
    func (rws *http2responseWriterState) declareTrailer(k string)
    func (rws *http2responseWriterState) hasNonemptyTrailers() bool
    func (rws *http2responseWriterState) hasTrailers() bool
    func (rws *http2responseWriterState) promoteUndeclaredTrailers()
    func (rws *http2responseWriterState) writeChunk(p []byte) (n int, err error)
    func (rws *http2responseWriterState) writeHeader(code int)
type http2serverConn
    func (sc *http2serverConn) CloseConn() error
    func (sc *http2serverConn) Flush() error
    func (sc *http2serverConn) Framer() *http2Framer
    func (sc *http2serverConn) HeaderEncoder() (*hpack.Encoder, *bytes.Buffer)
    func (sc *http2serverConn) awaitGracefulShutdown(sharedCh <-chan struct{}, privateCh chan struct{})
    func (sc *http2serverConn) canonicalHeader(v string) string
    func (sc *http2serverConn) closeAllStreamsOnConnClose()
    func (sc *http2serverConn) closeStream(st *http2stream, err error)
    func (sc *http2serverConn) condlogf(err error, format string, args ...interface{})
    func (sc *http2serverConn) curOpenStreams() uint32
    func (sc *http2serverConn) goAway(code http2ErrCode)
    func (sc *http2serverConn) logf(format string, args ...interface{})
    func (sc *http2serverConn) maxHeaderListSize() uint32
    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) noteBodyRead(st *http2stream, n int)
    func (sc *http2serverConn) noteBodyReadFromHandler(st *http2stream, n int, err error)
    func (sc *http2serverConn) notePanic()
    func (sc *http2serverConn) onIdleTimer()
    func (sc *http2serverConn) onSettingsTimer()
    func (sc *http2serverConn) onShutdownTimer()
    func (sc *http2serverConn) processData(f *http2DataFrame) error
    func (sc *http2serverConn) processFrame(f http2Frame) error
    func (sc *http2serverConn) processFrameFromReader(res http2readFrameResult) bool
    func (sc *http2serverConn) processGoAway(f *http2GoAwayFrame) error
    func (sc *http2serverConn) processHeaders(f *http2MetaHeadersFrame) error
    func (sc *http2serverConn) processPing(f *http2PingFrame) error
    func (sc *http2serverConn) processPriority(f *http2PriorityFrame) error
    func (sc *http2serverConn) processResetStream(f *http2RSTStreamFrame) error
    func (sc *http2serverConn) processSetting(s http2Setting) error
    func (sc *http2serverConn) processSettingInitialWindowSize(val uint32) error
    func (sc *http2serverConn) processSettings(f *http2SettingsFrame) error
    func (sc *http2serverConn) processWindowUpdate(f *http2WindowUpdateFrame) error
    func (sc *http2serverConn) readFrames()
    func (sc *http2serverConn) readPreface() error
    func (sc *http2serverConn) rejectConn(err http2ErrCode, debug string)
    func (sc *http2serverConn) resetStream(se http2StreamError)
    func (sc *http2serverConn) runHandler(rw *http2responseWriter, req *Request, handler func(ResponseWriter, *Request))
    func (sc *http2serverConn) scheduleFrameWrite()
    func (sc *http2serverConn) sendServeMsg(msg interface{})
    func (sc *http2serverConn) sendWindowUpdate(st *http2stream, n int)
    func (sc *http2serverConn) sendWindowUpdate32(st *http2stream, n int32)
    func (sc *http2serverConn) serve()
    func (sc *http2serverConn) setConnState(state ConnState)
    func (sc *http2serverConn) shutDownIn(d time.Duration)
    func (sc *http2serverConn) startFrameWrite(wr http2FrameWriteRequest)
    func (sc *http2serverConn) startGracefulShutdown()
    func (sc *http2serverConn) startGracefulShutdownInternal()
    func (sc *http2serverConn) startPush(msg *http2startPushRequest)
    func (sc *http2serverConn) state(streamID uint32) (http2streamState, *http2stream)
    func (sc *http2serverConn) stopShutdownTimer()
    func (sc *http2serverConn) vlogf(format string, args ...interface{})
    func (sc *http2serverConn) write100ContinueHeaders(st *http2stream)
    func (sc *http2serverConn) writeDataFromHandler(stream *http2stream, data []byte, endStream bool) error
    func (sc *http2serverConn) writeFrame(wr http2FrameWriteRequest)
    func (sc *http2serverConn) writeFrameAsync(wr http2FrameWriteRequest)
    func (sc *http2serverConn) writeFrameFromHandler(wr http2FrameWriteRequest) error
    func (sc *http2serverConn) writeHeaders(st *http2stream, headerData *http2writeResHeaders) error
    func (sc *http2serverConn) wroteFrame(res http2frameWriteResult)
type http2serverInternalState
    func (s *http2serverInternalState) registerConn(sc *http2serverConn)
    func (s *http2serverInternalState) startGracefulShutdown()
    func (s *http2serverInternalState) unregisterConn(sc *http2serverConn)
type http2serverMessage
type http2sortPriorityNodeSiblings
    func (z http2sortPriorityNodeSiblings) Len() int
    func (z http2sortPriorityNodeSiblings) Less(i, k int) bool
    func (z http2sortPriorityNodeSiblings) Swap(i, k int)
type http2sorter
    func (s *http2sorter) Keys(h Header) []string
    func (s *http2sorter) Len() int
    func (s *http2sorter) Less(i, j int) bool
    func (s *http2sorter) SortStrings(ss []string)
    func (s *http2sorter) Swap(i, j int)
type http2startPushRequest
type http2stickyErrWriter
    func (sew http2stickyErrWriter) Write(p []byte) (n int, err error)
type http2stream
    func (st *http2stream) copyTrailersToHandlerRequest()
    func (st *http2stream) endStream()
    func (st *http2stream) isPushed() bool
    func (st *http2stream) onWriteTimeout()
    func (st *http2stream) processTrailerHeaders(f *http2MetaHeadersFrame) error
type http2streamEnder
type http2streamState
    func (st http2streamState) String() string
type http2stringWriter
type http2transportResponseBody
    func (b http2transportResponseBody) Close() error
    func (b http2transportResponseBody) Read(p []byte) (n int, err error)
type http2write100ContinueHeadersFrame
    func (w http2write100ContinueHeadersFrame) staysWithinBuffer(max int) bool
    func (w http2write100ContinueHeadersFrame) writeFrame(ctx http2writeContext) error
type http2writeContext
type http2writeData
    func (w *http2writeData) String() string
    func (w *http2writeData) staysWithinBuffer(max int) bool
    func (w *http2writeData) writeFrame(ctx http2writeContext) error
type http2writeFramer
type http2writeGoAway
    func (*http2writeGoAway) staysWithinBuffer(max int) bool
    func (p *http2writeGoAway) writeFrame(ctx http2writeContext) error
type http2writePingAck
    func (w http2writePingAck) staysWithinBuffer(max int) bool
    func (w http2writePingAck) writeFrame(ctx http2writeContext) error
type http2writePushPromise
    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 http2writeQueue
    func (q *http2writeQueue) consume(n int32) (http2FrameWriteRequest, bool)
    func (q *http2writeQueue) empty() bool
    func (q *http2writeQueue) push(wr http2FrameWriteRequest)
    func (q *http2writeQueue) shift() http2FrameWriteRequest
type http2writeQueuePool
    func (p *http2writeQueuePool) get() *http2writeQueue
    func (p *http2writeQueuePool) put(q *http2writeQueue)
type http2writeResHeaders
    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 http2writeSettings
    func (s http2writeSettings) staysWithinBuffer(max int) bool
    func (s http2writeSettings) writeFrame(ctx http2writeContext) error
type http2writeSettingsAck
    func (http2writeSettingsAck) staysWithinBuffer(max int) bool
    func (http2writeSettingsAck) writeFrame(ctx http2writeContext) error
type http2writeWindowUpdate
    func (wu http2writeWindowUpdate) staysWithinBuffer(max int) bool
    func (wu http2writeWindowUpdate) writeFrame(ctx http2writeContext) error
type httpError
    func (e *httpError) Error() string
    func (e *httpError) Temporary() bool
    func (e *httpError) Timeout() bool
type httpRange
    func (r httpRange) contentRange(size int64) string
    func (r httpRange) mimeHeader(contentType string, size int64) textproto.MIMEHeader
type initALPNRequest
    func (h initALPNRequest) BaseContext() context.Context
    func (h initALPNRequest) ServeHTTP(rw ResponseWriter, req *Request)
type keyValues
type loggingConn
    func (c *loggingConn) Close() (err error)
    func (c *loggingConn) Read(p []byte) (n int, err error)
    func (c *loggingConn) Write(p []byte) (n int, err error)
type maskedSig
    func (m *maskedSig) match(data []byte, firstNonWS int) string
type maxBytesReader
    func (l *maxBytesReader) Close() error
    func (l *maxBytesReader) Read(p []byte) (n int, err error)
type mp4Sig
    func (mp4Sig) match(data []byte, firstNonWS int) string
type muxEntry
    func appendSorted(es []muxEntry, e muxEntry) []muxEntry
type noBody
    func (noBody) Close() error
    func (noBody) Read([]byte) (int, error)
    func (noBody) WriteTo(io.Writer) (int64, error)
type nothingWrittenError
type onceCloseListener
    func (oc *onceCloseListener) Close() error
    func (oc *onceCloseListener) close()
type persistConn
    func (pc *persistConn) Read(p []byte) (n int, err error)
    func (pconn *persistConn) addTLS(name string, trace *httptrace.ClientTrace) error
    func (pc *persistConn) cancelRequest(err error)
    func (pc *persistConn) canceled() error
    func (pc *persistConn) close(err error)
    func (pc *persistConn) closeConnIfStillIdle()
    func (pc *persistConn) closeLocked(err error)
    func (pc *persistConn) gotIdleConnTrace(idleAt time.Time) (t httptrace.GotConnInfo)
    func (pc *persistConn) isBroken() bool
    func (pc *persistConn) isReused() bool
    func (pc *persistConn) mapRoundTripError(req *transportRequest, startBytesWritten int64, err error) error
    func (pc *persistConn) markReused()
    func (pc *persistConn) maxHeaderResponseSize() int64
    func (pc *persistConn) readLoop()
    func (pc *persistConn) readLoopPeekFailLocked(peekErr error)
    func (pc *persistConn) readResponse(rc requestAndChan, trace *httptrace.ClientTrace) (resp *Response, err error)
    func (pc *persistConn) roundTrip(req *transportRequest) (resp *Response, err error)
    func (pc *persistConn) shouldRetryRequest(req *Request, err error) bool
    func (pc *persistConn) waitForContinue(continueCh <-chan struct{}) func() bool
    func (pc *persistConn) writeLoop()
    func (pc *persistConn) wroteRequest() bool
type persistConnWriter
    func (w persistConnWriter) ReadFrom(r io.Reader) (n int64, err error)
    func (w persistConnWriter) Write(p []byte) (n int, err error)
type populateResponse
    func newPopulateResponseWriter() (*populateResponse, <-chan *Response)
    func (pr *populateResponse) Header() Header
    func (pr *populateResponse) Write(p []byte) (n int, err error)
    func (pr *populateResponse) WriteHeader(code int)
    func (pr *populateResponse) finish()
    func (pr *populateResponse) sendResponse()
type readResult
type readWriteCloserBody
    func (b *readWriteCloserBody) Read(p []byte) (n int, err error)
type redirectHandler
    func (rh *redirectHandler) ServeHTTP(w ResponseWriter, r *Request)
type requestAndChan
type requestBodyReadError
type response
    func (w *response) CloseNotify() <-chan bool
    func (w *response) Flush()
    func (w *response) Header() Header
    func (w *response) Hijack() (rwc net.Conn, buf *bufio.ReadWriter, err error)
    func (w *response) ReadFrom(src io.Reader) (n int64, err error)
    func (w *response) Write(data []byte) (n int, err error)
    func (w *response) WriteHeader(code int)
    func (w *response) WriteString(data string) (n int, err error)
    func (w *response) bodyAllowed() bool
    func (w *response) closedRequestBodyEarly() bool
    func (w *response) declareTrailer(k string)
    func (w *response) finalTrailers() Header
    func (w *response) finishRequest()
    func (w *response) needsSniff() bool
    func (w *response) requestTooLarge()
    func (w *response) sendExpectationFailed()
    func (w *response) shouldReuseConnection() bool
    func (w *response) write(lenData int, dataB []byte, dataS string) (n int, err error)
type responseAndError
type serverHandler
    func (sh serverHandler) ServeHTTP(rw ResponseWriter, req *Request)
type sniffSig
type socksAddr
    func (a *socksAddr) Network() string
    func (a *socksAddr) String() string
type socksAuthMethod
type socksCommand
    func (cmd socksCommand) String() string
type socksConn
    func (c *socksConn) BoundAddr() net.Addr
type socksDialer
    func socksNewDialer(network, address string) *socksDialer
    func (d *socksDialer) Dial(network, address string) (net.Conn, error)
    func (d *socksDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error)
    func (d *socksDialer) DialWithConn(ctx context.Context, c net.Conn, network, address string) (net.Addr, error)
    func (d *socksDialer) connect(ctx context.Context, c net.Conn, address string) (_ net.Addr, ctxErr error)
    func (d *socksDialer) pathAddrs(address string) (proxy, dst net.Addr, err error)
    func (d *socksDialer) validateTarget(network, address string) error
type socksReply
    func (code socksReply) String() string
type socksUsernamePassword
    func (up *socksUsernamePassword) Authenticate(ctx context.Context, rw io.ReadWriter, auth socksAuthMethod) error
type stringWriter
    func (w stringWriter) WriteString(s string) (n int, err error)
type tLogKey
type textSig
    func (textSig) match(data []byte, firstNonWS int) string
type timeoutHandler
    func (h *timeoutHandler) ServeHTTP(w ResponseWriter, r *Request)
    func (h *timeoutHandler) errorBody() string
type timeoutWriter
    func (tw *timeoutWriter) Header() Header
    func (tw *timeoutWriter) Push(target string, opts *PushOptions) error
    func (tw *timeoutWriter) Write(p []byte) (int, error)
    func (tw *timeoutWriter) WriteHeader(code int)
    func (tw *timeoutWriter) writeHeaderLocked(code int)
type tlsHandshakeTimeoutError
    func (tlsHandshakeTimeoutError) Error() string
    func (tlsHandshakeTimeoutError) Temporary() bool
    func (tlsHandshakeTimeoutError) Timeout() bool
type transferReader
    func (t *transferReader) fixTransferEncoding() error
    func (t *transferReader) protoAtLeast(m, n int) bool
type transferWriter
    func (t *transferWriter) doBodyCopy(dst io.Writer, src io.Reader) (n int64, err error)
    func (t *transferWriter) probeRequestBody()
    func (t *transferWriter) shouldSendChunkedRequestBody() bool
    func (t *transferWriter) shouldSendContentLength() bool
    func (t *transferWriter) unwrapBody() io.Reader
    func (t *transferWriter) writeBody(w io.Writer) error
    func (t *transferWriter) writeHeader(w io.Writer, trace *httptrace.ClientTrace) error
type transportReadFromServerError
    func (e transportReadFromServerError) Error() string
    func (e transportReadFromServerError) Unwrap() error
type transportRequest
    func (tr *transportRequest) extraHeaders() Header
    func (tr *transportRequest) logf(format string, args ...interface{})
    func (tr *transportRequest) setError(err error)
type unsupportedTEError
    func (uste *unsupportedTEError) Error() string
type wantConn
    func (w *wantConn) cancel(t *Transport, err error)
    func (w *wantConn) tryDeliver(pc *persistConn, err error) bool
    func (w *wantConn) waiting() bool
type wantConnQueue
    func (q *wantConnQueue) cleanFront() (cleaned bool)
    func (q *wantConnQueue) len() int
    func (q *wantConnQueue) peekFront() *wantConn
    func (q *wantConnQueue) popFront() *wantConn
    func (q *wantConnQueue) pushBack(w *wantConn)
type writeRequest
type writerOnly

Package files

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

Constants

const (
    http2cipher_TLS_NULL_WITH_NULL_NULL               uint16 = 0x0000
    http2cipher_TLS_RSA_WITH_NULL_MD5                 uint16 = 0x0001
    http2cipher_TLS_RSA_WITH_NULL_SHA                 uint16 = 0x0002
    http2cipher_TLS_RSA_EXPORT_WITH_RC4_40_MD5        uint16 = 0x0003
    http2cipher_TLS_RSA_WITH_RC4_128_MD5              uint16 = 0x0004
    http2cipher_TLS_RSA_WITH_RC4_128_SHA              uint16 = 0x0005
    http2cipher_TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5    uint16 = 0x0006
    http2cipher_TLS_RSA_WITH_IDEA_CBC_SHA             uint16 = 0x0007
    http2cipher_TLS_RSA_EXPORT_WITH_DES40_CBC_SHA     uint16 = 0x0008
    http2cipher_TLS_RSA_WITH_DES_CBC_SHA              uint16 = 0x0009
    http2cipher_TLS_RSA_WITH_3DES_EDE_CBC_SHA         uint16 = 0x000A
    http2cipher_TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA  uint16 = 0x000B
    http2cipher_TLS_DH_DSS_WITH_DES_CBC_SHA           uint16 = 0x000C
    http2cipher_TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA      uint16 = 0x000D
    http2cipher_TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA  uint16 = 0x000E
    http2cipher_TLS_DH_RSA_WITH_DES_CBC_SHA           uint16 = 0x000F
    http2cipher_TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA      uint16 = 0x0010
    http2cipher_TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x0011
    http2cipher_TLS_DHE_DSS_WITH_DES_CBC_SHA          uint16 = 0x0012
    http2cipher_TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA     uint16 = 0x0013
    http2cipher_TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x0014
    http2cipher_TLS_DHE_RSA_WITH_DES_CBC_SHA          uint16 = 0x0015
    http2cipher_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA     uint16 = 0x0016
    http2cipher_TLS_DH_anon_EXPORT_WITH_RC4_40_MD5    uint16 = 0x0017
    http2cipher_TLS_DH_anon_WITH_RC4_128_MD5          uint16 = 0x0018
    http2cipher_TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x0019
    http2cipher_TLS_DH_anon_WITH_DES_CBC_SHA          uint16 = 0x001A
    http2cipher_TLS_DH_anon_WITH_3DES_EDE_CBC_SHA     uint16 = 0x001B
    // Reserved uint16 =  0x001C-1D
    http2cipher_TLS_KRB5_WITH_DES_CBC_SHA             uint16 = 0x001E
    http2cipher_TLS_KRB5_WITH_3DES_EDE_CBC_SHA        uint16 = 0x001F
    http2cipher_TLS_KRB5_WITH_RC4_128_SHA             uint16 = 0x0020
    http2cipher_TLS_KRB5_WITH_IDEA_CBC_SHA            uint16 = 0x0021
    http2cipher_TLS_KRB5_WITH_DES_CBC_MD5             uint16 = 0x0022
    http2cipher_TLS_KRB5_WITH_3DES_EDE_CBC_MD5        uint16 = 0x0023
    http2cipher_TLS_KRB5_WITH_RC4_128_MD5             uint16 = 0x0024
    http2cipher_TLS_KRB5_WITH_IDEA_CBC_MD5            uint16 = 0x0025
    http2cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA   uint16 = 0x0026
    http2cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA   uint16 = 0x0027
    http2cipher_TLS_KRB5_EXPORT_WITH_RC4_40_SHA       uint16 = 0x0028
    http2cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5   uint16 = 0x0029
    http2cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5   uint16 = 0x002A
    http2cipher_TLS_KRB5_EXPORT_WITH_RC4_40_MD5       uint16 = 0x002B
    http2cipher_TLS_PSK_WITH_NULL_SHA                 uint16 = 0x002C
    http2cipher_TLS_DHE_PSK_WITH_NULL_SHA             uint16 = 0x002D
    http2cipher_TLS_RSA_PSK_WITH_NULL_SHA             uint16 = 0x002E
    http2cipher_TLS_RSA_WITH_AES_128_CBC_SHA          uint16 = 0x002F
    http2cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA       uint16 = 0x0030
    http2cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA       uint16 = 0x0031
    http2cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA      uint16 = 0x0032
    http2cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA      uint16 = 0x0033
    http2cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA      uint16 = 0x0034
    http2cipher_TLS_RSA_WITH_AES_256_CBC_SHA          uint16 = 0x0035
    http2cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA       uint16 = 0x0036
    http2cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA       uint16 = 0x0037
    http2cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA      uint16 = 0x0038
    http2cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA      uint16 = 0x0039
    http2cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA      uint16 = 0x003A
    http2cipher_TLS_RSA_WITH_NULL_SHA256              uint16 = 0x003B
    http2cipher_TLS_RSA_WITH_AES_128_CBC_SHA256       uint16 = 0x003C
    http2cipher_TLS_RSA_WITH_AES_256_CBC_SHA256       uint16 = 0x003D
    http2cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA256    uint16 = 0x003E
    http2cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA256    uint16 = 0x003F
    http2cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA256   uint16 = 0x0040
    http2cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA     uint16 = 0x0041
    http2cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA  uint16 = 0x0042
    http2cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA  uint16 = 0x0043
    http2cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0044
    http2cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0045
    http2cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0046
    // Reserved uint16 =  0x0047-4F
    // Reserved uint16 =  0x0050-58
    // Reserved uint16 =  0x0059-5C
    // Unassigned uint16 =  0x005D-5F
    // Reserved uint16 =  0x0060-66
    http2cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0x0067
    http2cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA256  uint16 = 0x0068
    http2cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA256  uint16 = 0x0069
    http2cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 uint16 = 0x006A
    http2cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 uint16 = 0x006B
    http2cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA256 uint16 = 0x006C
    http2cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA256 uint16 = 0x006D
    // Unassigned uint16 =  0x006E-83
    http2cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA        uint16 = 0x0084
    http2cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA     uint16 = 0x0085
    http2cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA     uint16 = 0x0086
    http2cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA    uint16 = 0x0087
    http2cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA    uint16 = 0x0088
    http2cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA    uint16 = 0x0089
    http2cipher_TLS_PSK_WITH_RC4_128_SHA                 uint16 = 0x008A
    http2cipher_TLS_PSK_WITH_3DES_EDE_CBC_SHA            uint16 = 0x008B
    http2cipher_TLS_PSK_WITH_AES_128_CBC_SHA             uint16 = 0x008C
    http2cipher_TLS_PSK_WITH_AES_256_CBC_SHA             uint16 = 0x008D
    http2cipher_TLS_DHE_PSK_WITH_RC4_128_SHA             uint16 = 0x008E
    http2cipher_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA        uint16 = 0x008F
    http2cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA         uint16 = 0x0090
    http2cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA         uint16 = 0x0091
    http2cipher_TLS_RSA_PSK_WITH_RC4_128_SHA             uint16 = 0x0092
    http2cipher_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA        uint16 = 0x0093
    http2cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA         uint16 = 0x0094
    http2cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA         uint16 = 0x0095
    http2cipher_TLS_RSA_WITH_SEED_CBC_SHA                uint16 = 0x0096
    http2cipher_TLS_DH_DSS_WITH_SEED_CBC_SHA             uint16 = 0x0097
    http2cipher_TLS_DH_RSA_WITH_SEED_CBC_SHA             uint16 = 0x0098
    http2cipher_TLS_DHE_DSS_WITH_SEED_CBC_SHA            uint16 = 0x0099
    http2cipher_TLS_DHE_RSA_WITH_SEED_CBC_SHA            uint16 = 0x009A
    http2cipher_TLS_DH_anon_WITH_SEED_CBC_SHA            uint16 = 0x009B
    http2cipher_TLS_RSA_WITH_AES_128_GCM_SHA256          uint16 = 0x009C
    http2cipher_TLS_RSA_WITH_AES_256_GCM_SHA384          uint16 = 0x009D
    http2cipher_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256      uint16 = 0x009E
    http2cipher_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384      uint16 = 0x009F
    http2cipher_TLS_DH_RSA_WITH_AES_128_GCM_SHA256       uint16 = 0x00A0
    http2cipher_TLS_DH_RSA_WITH_AES_256_GCM_SHA384       uint16 = 0x00A1
    http2cipher_TLS_DHE_DSS_WITH_AES_128_GCM_SHA256      uint16 = 0x00A2
    http2cipher_TLS_DHE_DSS_WITH_AES_256_GCM_SHA384      uint16 = 0x00A3
    http2cipher_TLS_DH_DSS_WITH_AES_128_GCM_SHA256       uint16 = 0x00A4
    http2cipher_TLS_DH_DSS_WITH_AES_256_GCM_SHA384       uint16 = 0x00A5
    http2cipher_TLS_DH_anon_WITH_AES_128_GCM_SHA256      uint16 = 0x00A6
    http2cipher_TLS_DH_anon_WITH_AES_256_GCM_SHA384      uint16 = 0x00A7
    http2cipher_TLS_PSK_WITH_AES_128_GCM_SHA256          uint16 = 0x00A8
    http2cipher_TLS_PSK_WITH_AES_256_GCM_SHA384          uint16 = 0x00A9
    http2cipher_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256      uint16 = 0x00AA
    http2cipher_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384      uint16 = 0x00AB
    http2cipher_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256      uint16 = 0x00AC
    http2cipher_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384      uint16 = 0x00AD
    http2cipher_TLS_PSK_WITH_AES_128_CBC_SHA256          uint16 = 0x00AE
    http2cipher_TLS_PSK_WITH_AES_256_CBC_SHA384          uint16 = 0x00AF
    http2cipher_TLS_PSK_WITH_NULL_SHA256                 uint16 = 0x00B0
    http2cipher_TLS_PSK_WITH_NULL_SHA384                 uint16 = 0x00B1
    http2cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256      uint16 = 0x00B2
    http2cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384      uint16 = 0x00B3
    http2cipher_TLS_DHE_PSK_WITH_NULL_SHA256             uint16 = 0x00B4
    http2cipher_TLS_DHE_PSK_WITH_NULL_SHA384             uint16 = 0x00B5
    http2cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256      uint16 = 0x00B6
    http2cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384      uint16 = 0x00B7
    http2cipher_TLS_RSA_PSK_WITH_NULL_SHA256             uint16 = 0x00B8
    http2cipher_TLS_RSA_PSK_WITH_NULL_SHA384             uint16 = 0x00B9
    http2cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256     uint16 = 0x00BA
    http2cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256  uint16 = 0x00BB
    http2cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256  uint16 = 0x00BC
    http2cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BD
    http2cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BE
    http2cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BF
    http2cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256     uint16 = 0x00C0
    http2cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256  uint16 = 0x00C1
    http2cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256  uint16 = 0x00C2
    http2cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C3
    http2cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C4
    http2cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C5
    // Unassigned uint16 =  0x00C6-FE
    http2cipher_TLS_EMPTY_RENEGOTIATION_INFO_SCSV uint16 = 0x00FF
    // Unassigned uint16 =  0x01-55,*
    http2cipher_TLS_FALLBACK_SCSV uint16 = 0x5600
    // Unassigned                                   uint16 = 0x5601 - 0xC000
    http2cipher_TLS_ECDH_ECDSA_WITH_NULL_SHA                 uint16 = 0xC001
    http2cipher_TLS_ECDH_ECDSA_WITH_RC4_128_SHA              uint16 = 0xC002
    http2cipher_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA         uint16 = 0xC003
    http2cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA          uint16 = 0xC004
    http2cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA          uint16 = 0xC005
    http2cipher_TLS_ECDHE_ECDSA_WITH_NULL_SHA                uint16 = 0xC006
    http2cipher_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA             uint16 = 0xC007
    http2cipher_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA        uint16 = 0xC008
    http2cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA         uint16 = 0xC009
    http2cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA         uint16 = 0xC00A
    http2cipher_TLS_ECDH_RSA_WITH_NULL_SHA                   uint16 = 0xC00B
    http2cipher_TLS_ECDH_RSA_WITH_RC4_128_SHA                uint16 = 0xC00C
    http2cipher_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA           uint16 = 0xC00D
    http2cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA            uint16 = 0xC00E
    http2cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA            uint16 = 0xC00F
    http2cipher_TLS_ECDHE_RSA_WITH_NULL_SHA                  uint16 = 0xC010
    http2cipher_TLS_ECDHE_RSA_WITH_RC4_128_SHA               uint16 = 0xC011
    http2cipher_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA          uint16 = 0xC012
    http2cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA           uint16 = 0xC013
    http2cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA           uint16 = 0xC014
    http2cipher_TLS_ECDH_anon_WITH_NULL_SHA                  uint16 = 0xC015
    http2cipher_TLS_ECDH_anon_WITH_RC4_128_SHA               uint16 = 0xC016
    http2cipher_TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA          uint16 = 0xC017
    http2cipher_TLS_ECDH_anon_WITH_AES_128_CBC_SHA           uint16 = 0xC018
    http2cipher_TLS_ECDH_anon_WITH_AES_256_CBC_SHA           uint16 = 0xC019
    http2cipher_TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA            uint16 = 0xC01A
    http2cipher_TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA        uint16 = 0xC01B
    http2cipher_TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA        uint16 = 0xC01C
    http2cipher_TLS_SRP_SHA_WITH_AES_128_CBC_SHA             uint16 = 0xC01D
    http2cipher_TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA         uint16 = 0xC01E
    http2cipher_TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA         uint16 = 0xC01F
    http2cipher_TLS_SRP_SHA_WITH_AES_256_CBC_SHA             uint16 = 0xC020
    http2cipher_TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA         uint16 = 0xC021
    http2cipher_TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA         uint16 = 0xC022
    http2cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256      uint16 = 0xC023
    http2cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384      uint16 = 0xC024
    http2cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256       uint16 = 0xC025
    http2cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384       uint16 = 0xC026
    http2cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256        uint16 = 0xC027
    http2cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384        uint16 = 0xC028
    http2cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256         uint16 = 0xC029
    http2cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384         uint16 = 0xC02A
    http2cipher_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256      uint16 = 0xC02B
    http2cipher_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384      uint16 = 0xC02C
    http2cipher_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256       uint16 = 0xC02D
    http2cipher_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384       uint16 = 0xC02E
    http2cipher_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256        uint16 = 0xC02F
    http2cipher_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384        uint16 = 0xC030
    http2cipher_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256         uint16 = 0xC031
    http2cipher_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384         uint16 = 0xC032
    http2cipher_TLS_ECDHE_PSK_WITH_RC4_128_SHA               uint16 = 0xC033
    http2cipher_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA          uint16 = 0xC034
    http2cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA           uint16 = 0xC035
    http2cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA           uint16 = 0xC036
    http2cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256        uint16 = 0xC037
    http2cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384        uint16 = 0xC038
    http2cipher_TLS_ECDHE_PSK_WITH_NULL_SHA                  uint16 = 0xC039
    http2cipher_TLS_ECDHE_PSK_WITH_NULL_SHA256               uint16 = 0xC03A
    http2cipher_TLS_ECDHE_PSK_WITH_NULL_SHA384               uint16 = 0xC03B
    http2cipher_TLS_RSA_WITH_ARIA_128_CBC_SHA256             uint16 = 0xC03C
    http2cipher_TLS_RSA_WITH_ARIA_256_CBC_SHA384             uint16 = 0xC03D
    http2cipher_TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256          uint16 = 0xC03E
    http2cipher_TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384          uint16 = 0xC03F
    http2cipher_TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256          uint16 = 0xC040
    http2cipher_TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384          uint16 = 0xC041
    http2cipher_TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256         uint16 = 0xC042
    http2cipher_TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384         uint16 = 0xC043
    http2cipher_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256         uint16 = 0xC044
    http2cipher_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384         uint16 = 0xC045
    http2cipher_TLS_DH_anon_WITH_ARIA_128_CBC_SHA256         uint16 = 0xC046
    http2cipher_TLS_DH_anon_WITH_ARIA_256_CBC_SHA384         uint16 = 0xC047
    http2cipher_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256     uint16 = 0xC048
    http2cipher_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384     uint16 = 0xC049
    http2cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256      uint16 = 0xC04A
    http2cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384      uint16 = 0xC04B
    http2cipher_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256       uint16 = 0xC04C
    http2cipher_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384       uint16 = 0xC04D
    http2cipher_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256        uint16 = 0xC04E
    http2cipher_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384        uint16 = 0xC04F
    http2cipher_TLS_RSA_WITH_ARIA_128_GCM_SHA256             uint16 = 0xC050
    http2cipher_TLS_RSA_WITH_ARIA_256_GCM_SHA384             uint16 = 0xC051
    http2cipher_TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256         uint16 = 0xC052
    http2cipher_TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384         uint16 = 0xC053
    http2cipher_TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256          uint16 = 0xC054
    http2cipher_TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384          uint16 = 0xC055
    http2cipher_TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256         uint16 = 0xC056
    http2cipher_TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384         uint16 = 0xC057
    http2cipher_TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256          uint16 = 0xC058
    http2cipher_TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384          uint16 = 0xC059
    http2cipher_TLS_DH_anon_WITH_ARIA_128_GCM_SHA256         uint16 = 0xC05A
    http2cipher_TLS_DH_anon_WITH_ARIA_256_GCM_SHA384         uint16 = 0xC05B
    http2cipher_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256     uint16 = 0xC05C
    http2cipher_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384     uint16 = 0xC05D
    http2cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256      uint16 = 0xC05E
    http2cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384      uint16 = 0xC05F
    http2cipher_TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256       uint16 = 0xC060
    http2cipher_TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384       uint16 = 0xC061
    http2cipher_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256        uint16 = 0xC062
    http2cipher_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384        uint16 = 0xC063
    http2cipher_TLS_PSK_WITH_ARIA_128_CBC_SHA256             uint16 = 0xC064
    http2cipher_TLS_PSK_WITH_ARIA_256_CBC_SHA384             uint16 = 0xC065
    http2cipher_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256         uint16 = 0xC066
    http2cipher_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384         uint16 = 0xC067
    http2cipher_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256         uint16 = 0xC068
    http2cipher_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384         uint16 = 0xC069
    http2cipher_TLS_PSK_WITH_ARIA_128_GCM_SHA256             uint16 = 0xC06A
    http2cipher_TLS_PSK_WITH_ARIA_256_GCM_SHA384             uint16 = 0xC06B
    http2cipher_TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256         uint16 = 0xC06C
    http2cipher_TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384         uint16 = 0xC06D
    http2cipher_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256         uint16 = 0xC06E
    http2cipher_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384         uint16 = 0xC06F
    http2cipher_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256       uint16 = 0xC070
    http2cipher_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384       uint16 = 0xC071
    http2cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC072
    http2cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC073
    http2cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256  uint16 = 0xC074
    http2cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384  uint16 = 0xC075
    http2cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256   uint16 = 0xC076
    http2cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384   uint16 = 0xC077
    http2cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256    uint16 = 0xC078
    http2cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384    uint16 = 0xC079
    http2cipher_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256         uint16 = 0xC07A
    http2cipher_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384         uint16 = 0xC07B
    http2cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256     uint16 = 0xC07C
    http2cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384     uint16 = 0xC07D
    http2cipher_TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256      uint16 = 0xC07E
    http2cipher_TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384      uint16 = 0xC07F
    http2cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256     uint16 = 0xC080
    http2cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384     uint16 = 0xC081
    http2cipher_TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256      uint16 = 0xC082
    http2cipher_TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384      uint16 = 0xC083
    http2cipher_TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256     uint16 = 0xC084
    http2cipher_TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384     uint16 = 0xC085
    http2cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC086
    http2cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC087
    http2cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256  uint16 = 0xC088
    http2cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384  uint16 = 0xC089
    http2cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256   uint16 = 0xC08A
    http2cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384   uint16 = 0xC08B
    http2cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256    uint16 = 0xC08C
    http2cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384    uint16 = 0xC08D
    http2cipher_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256         uint16 = 0xC08E
    http2cipher_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384         uint16 = 0xC08F
    http2cipher_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256     uint16 = 0xC090
    http2cipher_TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384     uint16 = 0xC091
    http2cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256     uint16 = 0xC092
    http2cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384     uint16 = 0xC093
    http2cipher_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256         uint16 = 0xC094
    http2cipher_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384         uint16 = 0xC095
    http2cipher_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256     uint16 = 0xC096
    http2cipher_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384     uint16 = 0xC097
    http2cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256     uint16 = 0xC098
    http2cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384     uint16 = 0xC099
    http2cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256   uint16 = 0xC09A
    http2cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384   uint16 = 0xC09B
    http2cipher_TLS_RSA_WITH_AES_128_CCM                     uint16 = 0xC09C
    http2cipher_TLS_RSA_WITH_AES_256_CCM                     uint16 = 0xC09D
    http2cipher_TLS_DHE_RSA_WITH_AES_128_CCM                 uint16 = 0xC09E
    http2cipher_TLS_DHE_RSA_WITH_AES_256_CCM                 uint16 = 0xC09F
    http2cipher_TLS_RSA_WITH_AES_128_CCM_8                   uint16 = 0xC0A0
    http2cipher_TLS_RSA_WITH_AES_256_CCM_8                   uint16 = 0xC0A1
    http2cipher_TLS_DHE_RSA_WITH_AES_128_CCM_8               uint16 = 0xC0A2
    http2cipher_TLS_DHE_RSA_WITH_AES_256_CCM_8               uint16 = 0xC0A3
    http2cipher_TLS_PSK_WITH_AES_128_CCM                     uint16 = 0xC0A4
    http2cipher_TLS_PSK_WITH_AES_256_CCM                     uint16 = 0xC0A5
    http2cipher_TLS_DHE_PSK_WITH_AES_128_CCM                 uint16 = 0xC0A6
    http2cipher_TLS_DHE_PSK_WITH_AES_256_CCM                 uint16 = 0xC0A7
    http2cipher_TLS_PSK_WITH_AES_128_CCM_8                   uint16 = 0xC0A8
    http2cipher_TLS_PSK_WITH_AES_256_CCM_8                   uint16 = 0xC0A9
    http2cipher_TLS_PSK_DHE_WITH_AES_128_CCM_8               uint16 = 0xC0AA
    http2cipher_TLS_PSK_DHE_WITH_AES_256_CCM_8               uint16 = 0xC0AB
    http2cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CCM             uint16 = 0xC0AC
    http2cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CCM             uint16 = 0xC0AD
    http2cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8           uint16 = 0xC0AE
    http2cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8           uint16 = 0xC0AF
    // Unassigned uint16 =  0xC0B0-FF
    // Unassigned uint16 =  0xC1-CB,*
    // Unassigned uint16 =  0xCC00-A7
    http2cipher_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256   uint16 = 0xCCA8
    http2cipher_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCA9
    http2cipher_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256     uint16 = 0xCCAA
    http2cipher_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256         uint16 = 0xCCAB
    http2cipher_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256   uint16 = 0xCCAC
    http2cipher_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256     uint16 = 0xCCAD
    http2cipher_TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256     uint16 = 0xCCAE
)
const (
    http2dialOnMiss   = true
    http2noDialOnMiss = false
)
const (
    http2minMaxFrameSize = 1 << 14
    http2maxFrameSize    = 1<<24 - 1
)
const (
    // ClientPreface is the string that must be sent by new
    // connections from clients.
    http2ClientPreface = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"

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

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

    // http://http2.github.io/http2-spec/#SettingValues
    http2initialHeaderTableSize = 4096

    http2initialWindowSize = 65535 // 6.9.2 Initial Flow Control Window Size

    http2defaultMaxReadFrameSize = 1 << 20
)
const (
    http2prefaceTimeout         = 10 * time.Second
    http2firstSettingsTimeout   = 2 * time.Second // should be in-flight with preface anyway
    http2handlerChunkWriteSize  = 4 << 10
    http2defaultMaxStreams      = 250 // TODO: make this 100 as the GFE seems to?
    http2maxQueuedControlFrames = 10000
)
const (
    // transportDefaultConnFlow is how many connection-level flow control
    // tokens we give the server at start-up, past the default 64k.
    http2transportDefaultConnFlow = 1 << 30

    // transportDefaultStreamFlow is how many stream-level flow
    // control tokens we announce to the peer, and how many bytes
    // we buffer per stream.
    http2transportDefaultStreamFlow = 4 << 20

    // transportDefaultStreamMinRefresh is the minimum number of bytes we'll send
    // a stream-level WINDOW_UPDATE for at a time.
    http2transportDefaultStreamMinRefresh = 4 << 10

    http2defaultUserAgent = "Go-http-client/2.0"
)

Common HTTP methods.

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

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

Constants for readRequest's deleteHostHeader parameter.

const (
    deleteHostHeader = true
    keepHostHeader   = false
)

Wire protocol constants.

const (
    socksVersion5 = 0x05

    socksAddrTypeIPv4 = 0x01
    socksAddrTypeFQDN = 0x03
    socksAddrTypeIPv6 = 0x04

    socksCmdConnect socksCommand = 0x01 // establishes an active-open forward proxy connection
    sockscmdBind    socksCommand = 0x02 // establishes a passive-open forward proxy connection

    socksAuthMethodNotRequired         socksAuthMethod = 0x00 // no authentication required
    socksAuthMethodUsernamePassword    socksAuthMethod = 0x02 // use username/password
    socksAuthMethodNoAcceptableMethods socksAuthMethod = 0xff // no acceptable authentication methods

    socksStatusSucceeded socksReply = 0x00
)
const (
    socksauthUsernamePasswordVersion = 0x01
    socksauthStatusSucceeded         = 0x00
)

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

const (
    StatusContinue           = 100 // RFC 7231, 6.2.1
    StatusSwitchingProtocols = 101 // RFC 7231, 6.2.2
    StatusProcessing         = 102 // RFC 2518, 10.1
    StatusEarlyHints         = 103 // RFC 8297

    StatusOK                   = 200 // RFC 7231, 6.3.1
    StatusCreated              = 201 // RFC 7231, 6.3.2
    StatusAccepted             = 202 // RFC 7231, 6.3.3
    StatusNonAuthoritativeInfo = 203 // RFC 7231, 6.3.4
    StatusNoContent            = 204 // RFC 7231, 6.3.5
    StatusResetContent         = 205 // RFC 7231, 6.3.6
    StatusPartialContent       = 206 // RFC 7233, 4.1
    StatusMultiStatus          = 207 // RFC 4918, 11.1
    StatusAlreadyReported      = 208 // RFC 5842, 7.1
    StatusIMUsed               = 226 // RFC 3229, 10.4.1

    StatusMultipleChoices   = 300 // RFC 7231, 6.4.1
    StatusMovedPermanently  = 301 // RFC 7231, 6.4.2
    StatusFound             = 302 // RFC 7231, 6.4.3
    StatusSeeOther          = 303 // RFC 7231, 6.4.4
    StatusNotModified       = 304 // RFC 7232, 4.1
    StatusUseProxy          = 305 // RFC 7231, 6.4.5
    _                       = 306 // RFC 7231, 6.4.6 (Unused)
    StatusTemporaryRedirect = 307 // RFC 7231, 6.4.7
    StatusPermanentRedirect = 308 // RFC 7538, 3

    StatusBadRequest                   = 400 // RFC 7231, 6.5.1
    StatusUnauthorized                 = 401 // RFC 7235, 3.1
    StatusPaymentRequired              = 402 // RFC 7231, 6.5.2
    StatusForbidden                    = 403 // RFC 7231, 6.5.3
    StatusNotFound                     = 404 // RFC 7231, 6.5.4
    StatusMethodNotAllowed             = 405 // RFC 7231, 6.5.5
    StatusNotAcceptable                = 406 // RFC 7231, 6.5.6
    StatusProxyAuthRequired            = 407 // RFC 7235, 3.2
    StatusRequestTimeout               = 408 // RFC 7231, 6.5.7
    StatusConflict                     = 409 // RFC 7231, 6.5.8
    StatusGone                         = 410 // RFC 7231, 6.5.9
    StatusLengthRequired               = 411 // RFC 7231, 6.5.10
    StatusPreconditionFailed           = 412 // RFC 7232, 4.2
    StatusRequestEntityTooLarge        = 413 // RFC 7231, 6.5.11
    StatusRequestURITooLong            = 414 // RFC 7231, 6.5.12
    StatusUnsupportedMediaType         = 415 // RFC 7231, 6.5.13
    StatusRequestedRangeNotSatisfiable = 416 // RFC 7233, 4.4
    StatusExpectationFailed            = 417 // RFC 7231, 6.5.14
    StatusTeapot                       = 418 // RFC 7168, 2.3.3
    StatusMisdirectedRequest           = 421 // RFC 7540, 9.1.2
    StatusUnprocessableEntity          = 422 // RFC 4918, 11.2
    StatusLocked                       = 423 // RFC 4918, 11.3
    StatusFailedDependency             = 424 // RFC 4918, 11.4
    StatusTooEarly                     = 425 // RFC 8470, 5.2.
    StatusUpgradeRequired              = 426 // RFC 7231, 6.5.15
    StatusPreconditionRequired         = 428 // RFC 6585, 3
    StatusTooManyRequests              = 429 // RFC 6585, 4
    StatusRequestHeaderFieldsTooLarge  = 431 // RFC 6585, 5
    StatusUnavailableForLegalReasons   = 451 // RFC 7725, 3

    StatusInternalServerError           = 500 // RFC 7231, 6.6.1
    StatusNotImplemented                = 501 // RFC 7231, 6.6.2
    StatusBadGateway                    = 502 // RFC 7231, 6.6.3
    StatusServiceUnavailable            = 503 // RFC 7231, 6.6.4
    StatusGatewayTimeout                = 504 // RFC 7231, 6.6.5
    StatusHTTPVersionNotSupported       = 505 // RFC 7231, 6.6.6
    StatusVariantAlsoNegotiates         = 506 // RFC 2295, 8.1
    StatusInsufficientStorage           = 507 // RFC 4918, 11.5
    StatusLoopDetected                  = 508 // RFC 5842, 7.2
    StatusNotExtended                   = 510 // RFC 2774, 7
    StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
)

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

const DefaultMaxHeaderBytes = 1 << 20 // 1 MB

DefaultMaxIdleConnsPerHost is the default value of Transport's MaxIdleConnsPerHost.

const DefaultMaxIdleConnsPerHost = 2

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 TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"

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

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

https://golang.org/pkg/net/http/#ResponseWriter
https://golang.org/pkg/net/http/#example_ResponseWriter_trailers
const TrailerPrefix = "Trailer:"

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

const bufferBeforeChunkingSize = 2048

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

const debugServerConnections = false
const (
    defaultMaxMemory = 32 << 20 // 32 MB
)

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 on a blacklist for some intrusion detection systems. See https://codereview.appspot.com/7532043.

const defaultUserAgent = "Go-http-client/1.1"

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

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

https://golang.org/pkg/net/http/#ResponseWriter
https://golang.org/pkg/net/http/#example_ResponseWriter_trailers
const http2TrailerPrefix = "Trailer:"

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 http2bufWriterPoolBufferSize = 4 << 10
const http2frameHeaderLen = 9
const http2maxAllocFrameSize = 512 << 10

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

const http2priorityDefaultWeight = 15 // 16 = 15 + 1

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

const maxInt64 = 1<<63 - 1

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 maxPostHandlerReadBytes = 256 << 10

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 maxWriteWaitBeforeConnReuse = 50 * 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 rstAvoidanceDelay = 500 * time.Millisecond

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

const sniffLen = 512

Variables

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 (
    http2dataChunkSizeClasses = []int{
        1 << 10,
        2 << 10,
        4 << 10,
        8 << 10,
        16 << 10,
    }
    http2dataChunkPools = [...]sync.Pool{
        {New: func() interface{} { return make([]byte, 1<<10) }},
        {New: func() interface{} { return make([]byte, 2<<10) }},
        {New: func() interface{} { return make([]byte, 4<<10) }},
        {New: func() interface{} { return make([]byte, 8<<10) }},
        {New: func() interface{} { return make([]byte, 16<<10) }},
    }
)
var (
    http2errMixPseudoHeaderTypes = errors.New("mix of request and response pseudo headers")
    http2errPseudoAfterRegular   = errors.New("pseudo header field after regular")
)
var (
    http2errStreamID    = errors.New("invalid stream ID")
    http2errDepStreamID = errors.New("invalid dependent stream ID")
    http2errPadLength   = errors.New("pad length too large")
    http2errPadBytes    = errors.New("padding bytes must all be zeros unless AllowIllegalWrites is enabled")
)
var (
    http2commonBuildOnce   sync.Once
    http2commonLowerHeader map[string]string // Go-Canonical-Case -> lower-case
    http2commonCanonHeader map[string]string // lower-case -> Go-Canonical-Case
)
var (
    http2VerboseLogs    bool
    http2logFrameWrites bool
    http2logFrameReads  bool
    http2inTests        bool
)
var (
    http2errInvalidHeaderFieldName  = errors.New("http2: invalid header field name")
    http2errInvalidHeaderFieldValue = errors.New("http2: invalid header field value")
)
var (
    http2errClientDisconnected = errors.New("client disconnected")
    http2errClosedBody         = errors.New("body closed by handler")
    http2errHandlerComplete    = errors.New("http2: request body closed due to handler exiting")
    http2errStreamClosed       = errors.New("http2: stream closed")
)

Test hooks.

var (
    http2testHookOnConn        func()
    http2testHookGetServerConn func(*http2serverConn)
    http2testHookOnPanicMu     *sync.Mutex // nil except in tests
    http2testHookOnPanic       func(sc *http2serverConn, panicVal interface{}) (rePanic bool)
)

Message values sent to serveMsgCh.

var (
    http2settingsTimerMsg    = new(http2serverMessage)
    http2idleTimerMsg        = new(http2serverMessage)
    http2shutdownTimerMsg    = new(http2serverMessage)
    http2gracefulShutdownMsg = new(http2serverMessage)
)

Optional http.ResponseWriter interfaces implemented.

var (
    _ CloseNotifier     = (*http2responseWriter)(nil)
    _ Flusher           = (*http2responseWriter)(nil)
    _ http2stringWriter = (*http2responseWriter)(nil)
)

Push errors.

var (
    http2ErrRecursivePush    = errors.New("http2: recursive push not allowed")
    http2ErrPushLimitReached = errors.New("http2: push would exceed peer's SETTINGS_MAX_CONCURRENT_STREAMS")
)
var (
    http2errClientConnClosed    = errors.New("http2: client conn is closed")
    http2errClientConnUnusable  = errors.New("http2: client conn not usable")
    http2errClientConnGotGoAway = errors.New("http2: Transport received Server's graceful shutdown GOAWAY")
)

internal error values; they don't escape to callers

var (
    // abort request body write; don't send cancel
    http2errStopReqBodyWrite = errors.New("http2: aborting request body write")

    // abort request body write, but send stream reset of cancel.
    http2errStopReqBodyWriteAndCancel = errors.New("http2: canceling request")

    http2errReqBodyTooLong = errors.New("http2: request body larger than specified content length")
)
var (
    http2errResponseHeaderListSize = errors.New("http2: response header list larger than advertised limit")
    http2errRequestHeaderListSize  = errors.New("http2: request header list larger than peer's advertised limit")
    http2errPseudoTrailers         = errors.New("http2: invalid pseudo header in trailers")
)
var (
    // verify that an io.Copy from NoBody won't require a buffer:
    _ io.WriterTo   = NoBody
    _ io.ReadCloser = NoBody
)
var (
    // ErrNotSupported is returned by the Push method of Pusher
    // implementations to indicate that HTTP/2 Push support is not
    // available.
    ErrNotSupported = &ProtocolError{"feature not supported"}

    // Deprecated: ErrUnexpectedTrailer is no longer returned by
    // anything in the net/http package. Callers should not
    // compare errors against this variable.
    ErrUnexpectedTrailer = &ProtocolError{"trailer header without chunked transfer encoding"}

    // ErrMissingBoundary is returned by Request.MultipartReader when the
    // request's Content-Type does not include a "boundary" parameter.
    ErrMissingBoundary = &ProtocolError{"no multipart boundary param in Content-Type"}

    // ErrNotMultipart is returned by Request.MultipartReader when the
    // request's Content-Type is not multipart/form-data.
    ErrNotMultipart = &ProtocolError{"request Content-Type isn't multipart/form-data"}

    // Deprecated: ErrHeaderTooLong is no longer returned by
    // anything in the net/http package. Callers should not
    // compare errors against this variable.
    ErrHeaderTooLong = &ProtocolError{"header too long"}

    // Deprecated: ErrShortBody is no longer returned by
    // anything in the net/http package. Callers should not
    // compare errors against this variable.
    ErrShortBody = &ProtocolError{"entity body too short"}

    // Deprecated: ErrMissingContentLength is no longer returned by
    // anything in the net/http package. Callers should not
    // compare errors against this variable.
    ErrMissingContentLength = &ProtocolError{"missing ContentLength in HEAD response"}
)

Errors used by the HTTP server.

var (
    // ErrBodyNotAllowed is returned by ResponseWriter.Write calls
    // when the HTTP method or response code does not permit a
    // body.
    ErrBodyNotAllowed = errors.New("http: request method or response status code does not allow body")

    // ErrHijacked is returned by ResponseWriter.Write calls when
    // the underlying connection has been hijacked using the
    // Hijacker interface. A zero-byte write on a hijacked
    // connection will return ErrHijacked without any other side
    // effects.
    ErrHijacked = errors.New("http: connection has been hijacked")

    // ErrContentLength is returned by ResponseWriter.Write calls
    // when a Handler set a Content-Length response header with a
    // declared size and then attempted to write more bytes than
    // declared.
    ErrContentLength = errors.New("http: wrote more than the declared Content-Length")

    // Deprecated: ErrWriteAfterFlush is no longer returned by
    // anything in the net/http package. Callers should not
    // compare errors against this variable.
    ErrWriteAfterFlush = errors.New("unused")
)
var (
    // ServerContextKey is a context key. It can be used in HTTP
    // handlers with Context.Value to access the server that
    // started the handler. The associated value will be of
    // type *Server.
    ServerContextKey = &contextKey{"http-server"}

    // LocalAddrContextKey is a context key. It can be used in
    // HTTP handlers with Context.Value to access the local
    // address the connection arrived on.
    // The associated value will be of type net.Addr.
    LocalAddrContextKey = &contextKey{"local-addr"}
)
var (
    crlf       = []byte("\r\n")
    colonSpace = []byte(": ")
)
var (
    bufioReaderPool   sync.Pool
    bufioWriter2kPool sync.Pool
    bufioWriter4kPool sync.Pool
)
var (
    headerContentLength = []byte("Content-Length: ")
    headerDate          = []byte("Date: ")
)
var (
    uniqNameMu   sync.Mutex
    uniqNameNext = make(map[string]int)
)
var (
    socksnoDeadline   = time.Time{}
    socksaLongTimeAgo = time.Unix(1, 0)
)
var (
    suppressedHeaders304    = []string{"Content-Type", "Content-Length", "Transfer-Encoding"}
    suppressedHeadersNoBody = []string{"Content-Length", "Transfer-Encoding"}
)
var (
    singleCRLF = []byte("\r\n")
    doubleCRLF = []byte("\r\n\r\n")
)
var (
    // proxyConfigOnce guards proxyConfig
    envProxyOnce      sync.Once
    envProxyFuncValue func(*url.URL) (*url.URL, error)
)

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

var (
    errKeepAlivesDisabled = errors.New("http: putIdleConn: keep alives disabled")
    errConnBroken         = errors.New("http: putIdleConn: connection is in bad state")
    errCloseIdle          = errors.New("http: putIdleConn: CloseIdleConnections was called")
    errTooManyIdle        = errors.New("http: putIdleConn: too many idle connections")
    errTooManyIdleHost    = errors.New("http: putIdleConn: too many idle connections for host")
    errCloseIdleConns     = errors.New("http: CloseIdleConnections called")
    errReadLoopExiting    = errors.New("http: persistConn.readLoop exiting")
    errIdleConnTimeout    = errors.New("http: idle connection timeout")

    // errServerClosedIdle is not seen by users for idempotent requests, but may be
    // seen by a user if the server shuts down an idle connection and sends its FIN
    // in flight with already-written POST body bytes from the client.
    // See https://github.com/golang/go/issues/19943#issuecomment-355607646
    errServerClosedIdle = errors.New("http: server closed idle connection")
)

testHooks. Always non-nil.

var (
    testHookEnterRoundTrip   = nop
    testHookWaitResLoop      = nop
    testHookRoundTripRetried = nop
    testHookPrePendingDial   = nop
    testHookPostPendingDial  = nop

    testHookMu                     sync.Locker = fakeLocker{} // guards following
    testHookReadLoopBeforeNextRead             = nop
)

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

var DefaultClient = &Client{}

DefaultServeMux is the default ServeMux used by Serve.

var DefaultServeMux = &defaultServeMux

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 ErrAbortHandler = errors.New("net/http: abort Handler")

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 ErrBodyReadAfterClose = errors.New("http: invalid Read on closed Body")

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

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

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

var ErrLineTooLong = internal.ErrLineTooLong

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

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

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

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

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

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

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

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

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

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

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 ErrUseLastResponse = errors.New("net/http: use last response")

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 NoBody = noBody{}
var _ io.ReaderFrom = (*persistConnWriter)(nil)

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

var aLongTimeAgo = time.Unix(1, 0)
var cookieNameSanitizer = strings.NewReplacer("\n", "-", "\r", "-")
var copyBufPool = sync.Pool{
    New: func() interface{} {
        b := make([]byte, 32*1024)
        return &b
    },
}

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 errCallerOwnsConn = errors.New("read loop ending; caller owns writable underlying conn")

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

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

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 errNoOverlap = errors.New("invalid range: failed to overlap")
var errReadOnClosedResBody = errors.New("http: read on closed response body")

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

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

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 errSeeker = errors.New("seeker can't seek")
var errTimeout error = &httpError{err: "net/http: timeout awaiting response headers", timeout: true}
var errTooLarge = errors.New("http: request too large")
var errTrailerEOF = errors.New("http: unexpected EOF reading trailer")

Sorted the same as extraHeader.Write's loop.

var extraHeaderKeys = [][]byte{
    []byte("Content-Type"),
    []byte("Connection"),
    []byte("Transfer-Encoding"),
}
var headerNewlineToSpace = strings.NewReplacer("\n", " ", "\r", " ")
var headerSorterPool = sync.Pool{
    New: func() interface{} { return new(headerSorter) },
}
var htmlReplacer = strings.NewReplacer(
    "&", "&amp;",
    "<", "&lt;",
    ">", "&gt;",

    `"`, "&#34;",

    "'", "&#39;",
)
var http2DebugGoroutines = os.Getenv("DEBUG_HTTP2_GOROUTINES") == "1"

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

var http2ErrFrameTooLarge = errors.New("http2: frame too large")
var http2ErrNoCachedConn error = http2noCachedConnError{}
var http2bufWriterPool = sync.Pool{
    New: func() interface{} {
        return bufio.NewWriterSize(nil, http2bufWriterPoolBufferSize)
    },
}
var (
    http2clientPreface = []byte(http2ClientPreface)
)

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

var http2connHeaders = []string{
    "Connection",
    "Keep-Alive",
    "Proxy-Connection",
    "Transfer-Encoding",
    "Upgrade",
}
var http2errChanPool = sync.Pool{
    New: func() interface{} { return make(chan error, 1) },
}
var http2errClosedPipeWrite = errors.New("write on closed buffer")
var http2errClosedResponseBody = errors.New("http2: response body closed")
var http2errCodeName = map[http2ErrCode]string{
    http2ErrCodeNo:                 "NO_ERROR",
    http2ErrCodeProtocol:           "PROTOCOL_ERROR",
    http2ErrCodeInternal:           "INTERNAL_ERROR",
    http2ErrCodeFlowControl:        "FLOW_CONTROL_ERROR",
    http2ErrCodeSettingsTimeout:    "SETTINGS_TIMEOUT",
    http2ErrCodeStreamClosed:       "STREAM_CLOSED",
    http2ErrCodeFrameSize:          "FRAME_SIZE_ERROR",
    http2ErrCodeRefusedStream:      "REFUSED_STREAM",
    http2ErrCodeCancel:             "CANCEL",
    http2ErrCodeCompression:        "COMPRESSION_ERROR",
    http2ErrCodeConnect:            "CONNECT_ERROR",
    http2ErrCodeEnhanceYourCalm:    "ENHANCE_YOUR_CALM",
    http2ErrCodeInadequateSecurity: "INADEQUATE_SECURITY",
    http2ErrCodeHTTP11Required:     "HTTP_1_1_REQUIRED",
}

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 http2errHandlerPanicked = errors.New("http2: handler panicked")
var http2errInvalidTrailers = errors.New("http2: invalid trailers")
var http2errPrefaceTimeout = errors.New("timeout waiting for client preface")
var http2errReadEmpty = errors.New("read from empty dataBuffer")

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 http2errRequestCanceled = errors.New("net/http: request canceled")
var http2errTimeout error = &http2httpError{msg: "http2: timeout awaiting response headers", timeout: true}

frame header bytes. Used only by ReadFrameHeader.

var http2fhBytes = sync.Pool{
    New: func() interface{} {
        buf := make([]byte, http2frameHeaderLen)
        return &buf
    },
}
var http2flagName = map[http2FrameType]map[http2Flags]string{
    http2FrameData: {
        http2FlagDataEndStream: "END_STREAM",
        http2FlagDataPadded:    "PADDED",
    },
    http2FrameHeaders: {
        http2FlagHeadersEndStream:  "END_STREAM",
        http2FlagHeadersEndHeaders: "END_HEADERS",
        http2FlagHeadersPadded:     "PADDED",
        http2FlagHeadersPriority:   "PRIORITY",
    },
    http2FrameSettings: {
        http2FlagSettingsAck: "ACK",
    },
    http2FramePing: {
        http2FlagPingAck: "ACK",
    },
    http2FrameContinuation: {
        http2FlagContinuationEndHeaders: "END_HEADERS",
    },
    http2FramePushPromise: {
        http2FlagPushPromiseEndHeaders: "END_HEADERS",
        http2FlagPushPromisePadded:     "PADDED",
    },
}
var http2frameName = map[http2FrameType]string{
    http2FrameData:         "DATA",
    http2FrameHeaders:      "HEADERS",
    http2FramePriority:     "PRIORITY",
    http2FrameRSTStream:    "RST_STREAM",
    http2FrameSettings:     "SETTINGS",
    http2FramePushPromise:  "PUSH_PROMISE",
    http2FramePing:         "PING",
    http2FrameGoAway:       "GOAWAY",
    http2FrameWindowUpdate: "WINDOW_UPDATE",
    http2FrameContinuation: "CONTINUATION",
}
var http2frameParsers = map[http2FrameType]http2frameParser{
    http2FrameData:         http2parseDataFrame,
    http2FrameHeaders:      http2parseHeadersFrame,
    http2FramePriority:     http2parsePriorityFrame,
    http2FrameRSTStream:    http2parseRSTStreamFrame,
    http2FrameSettings:     http2parseSettingsFrame,
    http2FramePushPromise:  http2parsePushPromise,
    http2FramePing:         http2parsePingFrame,
    http2FrameGoAway:       http2parseGoAwayFrame,
    http2FrameWindowUpdate: http2parseWindowUpdateFrame,
    http2FrameContinuation: http2parseContinuationFrame,
}

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 http2goAwayTimeout = 1 * time.Second
var http2goroutineSpace = []byte("goroutine ")
var http2got1xxFuncForTests func(int, textproto.MIMEHeader) error
var http2littleBuf = sync.Pool{
    New: func() interface{} {
        buf := make([]byte, 64)
        return &buf
    },
}
var http2noBody io.ReadCloser = ioutil.NopCloser(bytes.NewReader(nil))
var http2padZeros = make([]byte, 255) // zeros for padding
var http2responseWriterStatePool = sync.Pool{
    New: func() interface{} {
        rws := &http2responseWriterState{}
        rws.bw = bufio.NewWriterSize(http2chunkWriter{rws}, http2handlerChunkWriteSize)
        return rws
    },
}
var http2settingName = map[http2SettingID]string{
    http2SettingHeaderTableSize:      "HEADER_TABLE_SIZE",
    http2SettingEnablePush:           "ENABLE_PUSH",
    http2SettingMaxConcurrentStreams: "MAX_CONCURRENT_STREAMS",
    http2SettingInitialWindowSize:    "INITIAL_WINDOW_SIZE",
    http2SettingMaxFrameSize:         "MAX_FRAME_SIZE",
    http2SettingMaxHeaderListSize:    "MAX_HEADER_LIST_SIZE",
}
var http2shutdownEnterWaitStateHook = func() {}
var http2sorterPool = sync.Pool{New: func() interface{} { return new(http2sorter) }}
var http2stateName = [...]string{
    http2stateIdle:             "Idle",
    http2stateOpen:             "Open",
    http2stateHalfClosedLocal:  "HalfClosedLocal",
    http2stateHalfClosedRemote: "HalfClosedRemote",
    http2stateClosed:           "Closed",
}
var http2writeDataPool = sync.Pool{
    New: func() interface{} { return new(http2writeData) },
}
var mp4 = []byte("mp4")
var mp4ftype = []byte("ftyp")

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 multipartByReader = &multipart.Form{
    Value: make(map[string][]string),
    File:  make(map[string][]*multipart.FileHeader),
}
var nopCloserType = reflect.TypeOf(ioutil.NopCloser(nil))

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 omitBundledHTTP2 bool
var portMap = map[string]string{
    "http":   "80",
    "https":  "443",
    "socks5": "1080",
}

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

var reqWriteExcludeHeader = map[string]bool{
    "Host":              true,
    "User-Agent":        true,
    "Content-Length":    true,
    "Transfer-Encoding": true,
    "Trailer":           true,
}
var respExcludeHeader = map[string]bool{
    "Content-Length":    true,
    "Transfer-Encoding": true,
    "Trailer":           true,
}

shutdownPollInterval is how often we poll for quiescence during Server.Shutdown. This is lower during tests, to speed up tests. 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.

var shutdownPollInterval = 500 * time.Millisecond

Data matching the table in section 6.

var sniffSignatures = []sniffSig{
    htmlSig("<!DOCTYPE HTML"),
    htmlSig("<HTML"),
    htmlSig("<HEAD"),
    htmlSig("<SCRIPT"),
    htmlSig("<IFRAME"),
    htmlSig("<H1"),
    htmlSig("<DIV"),
    htmlSig("<FONT"),
    htmlSig("<TABLE"),
    htmlSig("<A"),
    htmlSig("<STYLE"),
    htmlSig("<TITLE"),
    htmlSig("<B"),
    htmlSig("<BODY"),
    htmlSig("<BR"),
    htmlSig("<P"),
    htmlSig("<!--"),
    &maskedSig{
        mask:   []byte("\xFF\xFF\xFF\xFF\xFF"),
        pat:    []byte("<?xml"),
        skipWS: true,
        ct:     "text/xml; charset=utf-8"},
    &exactSig{[]byte("%PDF-"), "application/pdf"},
    &exactSig{[]byte("%!PS-Adobe-"), "application/postscript"},

    &maskedSig{
        mask: []byte("\xFF\xFF\x00\x00"),
        pat:  []byte("\xFE\xFF\x00\x00"),
        ct:   "text/plain; charset=utf-16be",
    },
    &maskedSig{
        mask: []byte("\xFF\xFF\x00\x00"),
        pat:  []byte("\xFF\xFE\x00\x00"),
        ct:   "text/plain; charset=utf-16le",
    },
    &maskedSig{
        mask: []byte("\xFF\xFF\xFF\x00"),
        pat:  []byte("\xEF\xBB\xBF\x00"),
        ct:   "text/plain; charset=utf-8",
    },

    &exactSig{[]byte("\x00\x00\x01\x00"), "image/x-icon"},
    &exactSig{[]byte("\x00\x00\x02\x00"), "image/x-icon"},
    &exactSig{[]byte("BM"), "image/bmp"},
    &exactSig{[]byte("GIF87a"), "image/gif"},
    &exactSig{[]byte("GIF89a"), "image/gif"},
    &maskedSig{
        mask: []byte("\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF"),
        pat:  []byte("RIFF\x00\x00\x00\x00WEBPVP"),
        ct:   "image/webp",
    },
    &exactSig{[]byte("\x89PNG\x0D\x0A\x1A\x0A"), "image/png"},
    &exactSig{[]byte("\xFF\xD8\xFF"), "image/jpeg"},

    &maskedSig{
        mask: []byte("\xFF\xFF\xFF\xFF"),
        pat:  []byte(".snd"),
        ct:   "audio/basic",
    },
    &maskedSig{
        mask: []byte("\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF"),
        pat:  []byte("FORM\x00\x00\x00\x00AIFF"),
        ct:   "audio/aiff",
    },
    &maskedSig{
        mask: []byte("\xFF\xFF\xFF"),
        pat:  []byte("ID3"),
        ct:   "audio/mpeg",
    },
    &maskedSig{
        mask: []byte("\xFF\xFF\xFF\xFF\xFF"),
        pat:  []byte("OggS\x00"),
        ct:   "application/ogg",
    },
    &maskedSig{
        mask: []byte("\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF"),
        pat:  []byte("MThd\x00\x00\x00\x06"),
        ct:   "audio/midi",
    },
    &maskedSig{
        mask: []byte("\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF"),
        pat:  []byte("RIFF\x00\x00\x00\x00AVI "),
        ct:   "video/avi",
    },
    &maskedSig{
        mask: []byte("\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF"),
        pat:  []byte("RIFF\x00\x00\x00\x00WAVE"),
        ct:   "audio/wave",
    },

    mp4Sig{},

    &exactSig{[]byte("\x1A\x45\xDF\xA3"), "video/webm"},

    &maskedSig{

        pat: []byte("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00LP"),

        mask: []byte("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF"),
        ct:   "application/vnd.ms-fontobject",
    },
    &exactSig{[]byte("\x00\x01\x00\x00"), "font/ttf"},
    &exactSig{[]byte("OTTO"), "font/otf"},
    &exactSig{[]byte("ttcf"), "font/collection"},
    &exactSig{[]byte("wOFF"), "font/woff"},
    &exactSig{[]byte("wOF2"), "font/woff2"},

    &exactSig{[]byte("\x1F\x8B\x08"), "application/x-gzip"},
    &exactSig{[]byte("PK\x03\x04"), "application/zip"},

    &exactSig{[]byte("Rar!\x1A\x07\x00"), "application/x-rar-compressed"},
    &exactSig{[]byte("Rar!\x1A\x07\x01\x00"), "application/x-rar-compressed"},

    &exactSig{[]byte("\x00\x61\x73\x6D"), "application/wasm"},

    textSig{},
}
var stateName = map[ConnState]string{
    StateNew:      "new",
    StateActive:   "active",
    StateIdle:     "idle",
    StateHijacked: "hijacked",
    StateClosed:   "closed",
}
var statusText = map[int]string{
    StatusContinue:           "Continue",
    StatusSwitchingProtocols: "Switching Protocols",
    StatusProcessing:         "Processing",
    StatusEarlyHints:         "Early Hints",

    StatusOK:                   "OK",
    StatusCreated:              "Created",
    StatusAccepted:             "Accepted",
    StatusNonAuthoritativeInfo: "Non-Authoritative Information",
    StatusNoContent:            "No Content",
    StatusResetContent:         "Reset Content",
    StatusPartialContent:       "Partial Content",
    StatusMultiStatus:          "Multi-Status",
    StatusAlreadyReported:      "Already Reported",
    StatusIMUsed:               "IM Used",

    StatusMultipleChoices:   "Multiple Choices",
    StatusMovedPermanently:  "Moved Permanently",
    StatusFound:             "Found",
    StatusSeeOther:          "See Other",
    StatusNotModified:       "Not Modified",
    StatusUseProxy:          "Use Proxy",
    StatusTemporaryRedirect: "Temporary Redirect",
    StatusPermanentRedirect: "Permanent Redirect",

    StatusBadRequest:                   "Bad Request",
    StatusUnauthorized:                 "Unauthorized",
    StatusPaymentRequired:              "Payment Required",
    StatusForbidden:                    "Forbidden",
    StatusNotFound:                     "Not Found",
    StatusMethodNotAllowed:             "Method Not Allowed",
    StatusNotAcceptable:                "Not Acceptable",
    StatusProxyAuthRequired:            "Proxy Authentication Required",
    StatusRequestTimeout:               "Request Timeout",
    StatusConflict:                     "Conflict",
    StatusGone:                         "Gone",
    StatusLengthRequired:               "Length Required",
    StatusPreconditionFailed:           "Precondition Failed",
    StatusRequestEntityTooLarge:        "Request Entity Too Large",
    StatusRequestURITooLong:            "Request URI Too Long",
    StatusUnsupportedMediaType:         "Unsupported Media Type",
    StatusRequestedRangeNotSatisfiable: "Requested Range Not Satisfiable",
    StatusExpectationFailed:            "Expectation Failed",
    StatusTeapot:                       "I'm a teapot",
    StatusMisdirectedRequest:           "Misdirected Request",
    StatusUnprocessableEntity:          "Unprocessable Entity",
    StatusLocked:                       "Locked",
    StatusFailedDependency:             "Failed Dependency",
    StatusTooEarly:                     "Too Early",
    StatusUpgradeRequired:              "Upgrade Required",
    StatusPreconditionRequired:         "Precondition Required",
    StatusTooManyRequests:              "Too Many Requests",
    StatusRequestHeaderFieldsTooLarge:  "Request Header Fields Too Large",
    StatusUnavailableForLegalReasons:   "Unavailable For Legal Reasons",

    StatusInternalServerError:           "Internal Server Error",
    StatusNotImplemented:                "Not Implemented",
    StatusBadGateway:                    "Bad Gateway",
    StatusServiceUnavailable:            "Service Unavailable",
    StatusGatewayTimeout:                "Gateway Timeout",
    StatusHTTPVersionNotSupported:       "HTTP Version Not Supported",
    StatusVariantAlsoNegotiates:         "Variant Also Negotiates",
    StatusInsufficientStorage:           "Insufficient Storage",
    StatusLoopDetected:                  "Loop Detected",
    StatusNotExtended:                   "Not Extended",
    StatusNetworkAuthenticationRequired: "Network Authentication Required",
}
var testHookClientDoResult func(retres *Response, reterr error)
var testHookServerServe func(*Server, net.Listener) // used if non-nil
var textprotoReaderPool sync.Pool
var timeFormats = []string{
    TimeFormat,
    time.RFC850,
    time.ANSIC,
}
var unixEpochTime = time.Unix(0, 0)
var zeroDialer net.Dialer

func CanonicalHeaderKey

func CanonicalHeaderKey(s string) string

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

func DetectContentType

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 Error

func Error(w ResponseWriter, error string, code int)

Error replies to the request with the specified error message and HTTP code. It does not otherwise end the request; the caller should ensure no further writes are done to w. The error message should be plain text.

func Get

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.

Example

func Handle

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.

Example

func HandleFunc

func HandleFunc(pattern string, handler func(ResponseWriter, *Request))

HandleFunc registers the handler function for the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched.

Example

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 ListenAndServe

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.

Example

func ListenAndServeTLS

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.

Example

func MaxBytesReader

func MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser

MaxBytesReader is similar to io.LimitReader but is intended for limiting the size of incoming request bodies. In contrast to io.LimitReader, MaxBytesReader's result is a ReadCloser, returns a non-EOF error for a Read beyond the limit, and closes the underlying reader when its Close method is called.

MaxBytesReader prevents clients from accidentally or maliciously sending a large request and wasting server resources.

func NewRequest

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

NewRequest wraps NewRequestWithContext using the background context.

func NewRequestWithContext 1.13

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 NotFound

func NotFound(w ResponseWriter, r *Request)

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

func ParseHTTPVersion

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

ParseHTTPVersion parses an HTTP version string. "HTTP/1.0" returns (1, 0, true).

func ParseTime 1.1

func ParseTime(text string) (t time.Time, err error)

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

func Post

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

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 ProxyFromEnvironment

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

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 ReadRequest

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 ReadResponse

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 Redirect

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 Serve

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 ServeContent

func ServeContent(w ResponseWriter, req *Request, name string, modtime time.Time, content io.ReadSeeker)

ServeContent replies to the request using the content in the provided ReadSeeker. The main benefit of ServeContent over io.Copy is that it handles Range requests properly, sets the MIME type, and handles If-Match, If-Unmodified-Since, If-None-Match, If-Modified-Since, and If-Range requests.

If the response's Content-Type header is not set, ServeContent first tries to deduce the type from name's file extension and, if that fails, falls back to reading the first block of the content and passing it to DetectContentType. The name is otherwise unused; in particular it can be empty and is never sent in the response.

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

The content's Seek method must work: ServeContent uses a seek to the end of the content to determine its size.

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

Note that *os.File implements the io.ReadSeeker interface.

func ServeFile

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 ServeTLS 1.9

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 SetCookie

func SetCookie(w ResponseWriter, cookie *Cookie)

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

func StatusText

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 alwaysFalse

func alwaysFalse() bool

func appendTime

func appendTime(b []byte, t time.Time) []byte

appendTime is a non-allocating version of []byte(t.UTC().Format(TimeFormat))

func basicAuth

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 bodyAllowedForStatus

func bodyAllowedForStatus(status int) bool

bodyAllowedForStatus reports whether a given response status code permits a body. See RFC 7230, section 3.3.

func bufioWriterPool

func bufioWriterPool(size int) *sync.Pool

func canonicalAddr

func canonicalAddr(url *url.URL) string

canonicalAddr returns url.Host but always with a ":port" suffix

func checkPreconditions

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 checkWriteHeaderCode

func checkWriteHeaderCode(code int)

func chunked

func chunked(te []string) bool

Checks whether chunked is part of the encodings stack

func cleanHost

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 (Host = uri-host [ ":" port ]")
https://tools.ietf.org/html/rfc7230#section-2.7 (uri-host -> rfc3986's host)
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 cleanPath

func cleanPath(p string) string

cleanPath returns the canonical path for p, eliminating . and .. elements.

func cloneMultipartFileHeader

func cloneMultipartFileHeader(fh *multipart.FileHeader) *multipart.FileHeader

func cloneMultipartForm

func cloneMultipartForm(f *multipart.Form) *multipart.Form

func cloneTLSConfig

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 cloneURL

func cloneURL(u *url.URL) *url.URL

func cloneURLValues

func cloneURLValues(v url.Values) url.Values

func containsDotDot

func containsDotDot(v string) bool

func copyValues

func copyValues(dst, src url.Values)

func defaultCheckRedirect

func defaultCheckRedirect(req *Request, via []*Request) error

func dirList

func dirList(w ResponseWriter, r *Request, f File)

func envProxyFunc

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 etagStrongMatch

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

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 fixLength

func fixLength(isResponse bool, status int, requestMethod string, header Header, te []string) (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 fixPragmaCacheControl

func fixPragmaCacheControl(header Header)

RFC 7234, section 5.4: Should treat

Pragma: no-cache

like

Cache-Control: no-cache

func fixTrailer

func fixTrailer(header Header, te []string) (Header, error)

Parse the trailer header

func foreachHeaderElement

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 hasPort

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 hasToken

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 hexEscapeNonASCII

func hexEscapeNonASCII(s string) string

func htmlEscape

func htmlEscape(s string) string

func http1ServerSupportsRequest

func http1ServerSupportsRequest(req *Request) bool

http1ServerSupportsRequest reports whether Go's HTTP/1.x server supports the given request.

func http2ConfigureServer

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 http2ConfigureTransport

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.

func http2ReadFrameHeader

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 http2actualContentLength

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 http2authorityAddr

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 http2awaitRequestCancel

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 http2bodyAllowedForStatus

func http2bodyAllowedForStatus(status int) bool

bodyAllowedForStatus reports whether a given response status code permits a body. See RFC 7230, section 3.3.

func http2buildCommonHeaderMaps

func http2buildCommonHeaderMaps()

func http2buildCommonHeaderMapsOnce

func http2buildCommonHeaderMapsOnce()

func http2canRetryError

func http2canRetryError(err error) bool

func http2checkConnHeaders

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 http2checkPriority

func http2checkPriority(streamID uint32, p http2PriorityParam) error

func http2checkValidHTTP2RequestHeaders

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 http2checkWriteHeaderCode

func http2checkWriteHeaderCode(code int)

checkWriteHeaderCode is a copy of net/http's checkWriteHeaderCode.

func http2commaSeparatedTrailers

func http2commaSeparatedTrailers(req *Request) (string, error)

func http2configureTransport

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

func http2curGoroutineID

func http2curGoroutineID() uint64

func http2cutoff64

func http2cutoff64(base int) uint64

Return the first number n such that n*base >= 1<<64.

func http2encKV

func http2encKV(enc *hpack.Encoder, k, v string)

func http2encodeHeaders

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 http2errno

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 http2foreachHeaderElement

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 http2getDataBufferChunk

func http2getDataBufferChunk(size int64) []byte

func http2h1ServerKeepAlivesDisabled

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 http2handleHeaderListTooLong

func http2handleHeaderListTooLong(w ResponseWriter, r *Request)

func http2httpCodeString

func http2httpCodeString(code int) string

func http2isBadCipher

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 http2isClosedConnError

func http2isClosedConnError(err error) bool

isClosedConnError reports whether err is an error from use of a closed network connection.

func http2isConnectionCloseRequest

func http2isConnectionCloseRequest(req *Request) bool

isConnectionCloseRequest reports whether req should use its own connection for a single request and then close the connection.

func http2isEOFOrNetReadError

func http2isEOFOrNetReadError(err error) bool

func http2isNoCachedConnError

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 http2lowerHeader

func http2lowerHeader(v string) string

func http2mustUint31

func http2mustUint31(v int32) uint32

func http2parseContinuationFrame

func http2parseContinuationFrame(_ *http2frameCache, fh http2FrameHeader, p []byte) (http2Frame, error)

func http2parseDataFrame

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

func http2parseGoAwayFrame

func http2parseGoAwayFrame(_ *http2frameCache, fh http2FrameHeader, p []byte) (http2Frame, error)

func http2parseHeadersFrame

func http2parseHeadersFrame(_ *http2frameCache, fh http2FrameHeader, p []byte) (_ http2Frame, err error)

func http2parsePingFrame

func http2parsePingFrame(_ *http2frameCache, fh http2FrameHeader, payload []byte) (http2Frame, error)

func http2parsePriorityFrame

func http2parsePriorityFrame(_ *http2frameCache, fh http2FrameHeader, payload []byte) (http2Frame, error)

func http2parsePushPromise

func http2parsePushPromise(_ *http2frameCache, fh http2FrameHeader, p []byte) (_ http2Frame, err error)

func http2parseRSTStreamFrame

func http2parseRSTStreamFrame(_ *http2frameCache, fh http2FrameHeader, p []byte) (http2Frame, error)

func http2parseSettingsFrame

func http2parseSettingsFrame(_ *http2frameCache, fh http2FrameHeader, p []byte) (http2Frame, error)

func http2parseUintBytes

func http2parseUintBytes(s []byte, base int, bitSize int) (n uint64, err error)

parseUintBytes is like strconv.ParseUint, but using a []byte.

func http2parseUnknownFrame

func http2parseUnknownFrame(_ *http2frameCache, fh http2FrameHeader, p []byte) (http2Frame, error)

func http2parseWindowUpdateFrame

func http2parseWindowUpdateFrame(_ *http2frameCache, fh http2FrameHeader, p []byte) (http2Frame, error)

func http2putDataBufferChunk

func http2putDataBufferChunk(p []byte)

func http2readByte

func http2readByte(p []byte) (remain []byte, b byte, err error)

func http2readFrameHeader

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

func http2readUint32

func http2readUint32(p []byte) (remain []byte, v uint32, err error)

func http2registerHTTPSProtocol

func http2registerHTTPSProtocol(t *Transport, rt http2noDialH2RoundTripper) (err error)

registerHTTPSProtocol calls Transport.RegisterProtocol but converting panics into errors.

func http2serverConnBaseContext

func http2serverConnBaseContext(c net.Conn, opts *http2ServeConnOpts) (ctx context.Context, cancel func())

func http2shouldRetryRequest

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 http2shouldSendReqContentLength

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 http2splitHeaderBlock

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 http2strSliceContains

func http2strSliceContains(ss []string, s string) bool

func http2summarizeFrame

func http2summarizeFrame(f http2Frame) string

func http2terminalReadFrameError

func http2terminalReadFrameError(err error) bool

terminalReadFrameError reports whether err is an unrecoverable error from ReadFrame and no other frames should be read.

func http2traceFirstResponseByte

func http2traceFirstResponseByte(trace *httptrace.ClientTrace)

func http2traceGetConn

func http2traceGetConn(req *Request, hostPort string)

func http2traceGot100Continue

func http2traceGot100Continue(trace *httptrace.ClientTrace)

func http2traceGot1xxResponseFunc

func http2traceGot1xxResponseFunc(trace *httptrace.ClientTrace) func(int, textproto.MIMEHeader) error

func http2traceGotConn

func http2traceGotConn(req *Request, cc *http2ClientConn, reused bool)

func http2traceHasWroteHeaderField

func http2traceHasWroteHeaderField(trace *httptrace.ClientTrace) bool

func http2traceWait100Continue

func http2traceWait100Continue(trace *httptrace.ClientTrace)

func http2traceWroteHeaderField

func http2traceWroteHeaderField(trace *httptrace.ClientTrace, k, v string)

func http2traceWroteHeaders

func http2traceWroteHeaders(trace *httptrace.ClientTrace)

func http2traceWroteRequest

func http2traceWroteRequest(trace *httptrace.ClientTrace, err error)

func http2validPseudoPath

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 http2validStreamID

func http2validStreamID(streamID uint32) bool

func http2validStreamIDOrZero

func http2validStreamIDOrZero(streamID uint32) bool

func http2validWireHeaderFieldName

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 http2writeEndsStream

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 idnaASCII

func idnaASCII(v string) (string, error)

func init

func init()

func is408Message

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 isASCII

func isASCII(s string) bool

func isCommonNetReadError

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 isCookieDomainName

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 isCookieNameValid

func isCookieNameValid(raw string) bool

func isDomainOrSubdomain

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 isIdentity

func isIdentity(te []string) bool

Checks whether the encoding is explicitly "identity".

func isKnownInMemoryReader

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 isNotToken

func isNotToken(r rune) bool

func isSlashRune

func isSlashRune(r rune) bool

func isTT

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 isTokenBoundary

func isTokenBoundary(b byte) bool

func isUnsupportedTEError

func isUnsupportedTEError(err error) bool

isUnsupportedTEError checks if the error is of type unsupportedTEError. It is usually invoked with a non-nil err.

func isWS

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 isZeroTime

func isZeroTime(t time.Time) bool

isZeroTime reports whether t is obviously unspecified (either zero or Unix()=0).

func knownRoundTripperImpl

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 localRedirect

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 logf

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 mapDirOpenError

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 os.ErrNotExist. See Issue 18984.

func mergeSetHeader

func mergeSetHeader(dst *Header, src Header)

func newBufioReader

func newBufioReader(r io.Reader) *bufio.Reader

func newBufioWriterSize

func newBufioWriterSize(w io.Writer, size int) *bufio.Writer

func newLoggingConn

func newLoggingConn(baseName string, c net.Conn) net.Conn

func newReadWriteCloserBody

func newReadWriteCloserBody(br *bufio.Reader, rwc io.ReadWriteCloser) io.ReadWriteCloser

func newTextprotoReader

func newTextprotoReader(br *bufio.Reader) *textproto.Reader

func newTransferWriter

func newTransferWriter(r interface{}) (t *transferWriter, err error)

func noResponseBodyExpected

func noResponseBodyExpected(requestMethod string) bool

func nop

func nop()

func numLeadingCRorLF

func numLeadingCRorLF(v []byte) (n int)

func parseBasicAuth

func parseBasicAuth(auth string) (username, password string, ok bool)

parseBasicAuth parses an HTTP Basic Authentication string. "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" returns ("Aladdin", "open sesame", true).

func parseContentLength

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 parseCookieValue

func parseCookieValue(raw string, allowDoubleQuote bool) (string, bool)

func parsePostForm

func parsePostForm(r *Request) (vs url.Values, err error)

func parseRange

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 parseRequestLine

func parseRequestLine(line string) (method, requestURI, proto string, ok bool)

parseRequestLine parses "GET /foo HTTP/1.1" into its three parts.

func putBufioReader

func putBufioReader(br *bufio.Reader)

func putBufioWriter

func putBufioWriter(bw *bufio.Writer)

func putTextprotoReader

func putTextprotoReader(r *textproto.Reader)

func rangesMIMESize

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 readRequest

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

func readTransfer

func readTransfer(msg interface{}, r *bufio.Reader) (err error)

msg is *Request or *Response.

func redirectBehavior

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 refererForURL

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 registerOnHitEOF

func registerOnHitEOF(rc io.ReadCloser, fn func())

func relevantCaller

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 removeEmptyPort

func removeEmptyPort(host string) string

removeEmptyPort strips the empty port in ":port" to "" as mandated by RFC 3986 Section 6.2.3.

func removeZone

func removeZone(host string) string

removeZone removes IPv6 zone identifier from host. E.g., "[fe80::1%en0]:8080" to "[fe80::1]:8080"

func requestBodyRemains

func requestBodyRemains(rc io.ReadCloser) bool

requestBodyRemains reports whether future calls to Read on rc might yield more data.

func requestMethodUsuallyLacksBody

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 resetProxyConfig

func resetProxyConfig()

resetProxyConfig is used by tests.

func sanitizeCookieName

func sanitizeCookieName(n string) string

func sanitizeCookiePath

func sanitizeCookiePath(v string) string

path-av = "Path=" path-value path-value = <any CHAR except CTLs or ";">

func sanitizeCookieValue

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 sanitizeOrWarn

func sanitizeOrWarn(fieldName string, valid func(byte) bool, v string) string

func scanETag

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 seeUpcomingDoubleCRLF

func seeUpcomingDoubleCRLF(r *bufio.Reader) bool

func send

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 serveContent

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 serveFile

func serveFile(w ResponseWriter, r *Request, fs FileSystem, name string, redirect bool)

name is '/'-separated, not filepath.Separator.

func setLastModified

func setLastModified(w ResponseWriter, modtime time.Time)

func setRequestCancel

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 shouldClose

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 shouldCopyHeaderOnRedirect

func shouldCopyHeaderOnRedirect(headerKey string, initial, dest *url.URL) bool

func sockssplitHostPort

func sockssplitHostPort(address string) (string, int, error)

func srcIsRegularFile

func srcIsRegularFile(src io.Reader) (isRegular bool, err error)

func strSliceContains

func strSliceContains(ss []string, s string) bool

func stringContainsCTLByte

func stringContainsCTLByte(s string) bool

stringContainsCTLByte reports whether s contains any ASCII control character.

func stripHostPort

func stripHostPort(h string) string

stripHostPort returns h without any trailing ":<port>".

func stripPassword

func stripPassword(u *url.URL) string

func sumRangesSize

func sumRangesSize(ranges []httpRange) (size int64)

func suppressedHeaders

func suppressedHeaders(status int) []string

func timeBeforeContextDeadline

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 tlsRecordHeaderLooksLikeHTTP

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 toHTTPError

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 urlErrorOp

func urlErrorOp(method string) string

urlErrorOp returns the (*url.Error).Op value to use for the provided (*Request).Method value.

func validCookieDomain

func validCookieDomain(v string) bool

validCookieDomain reports whether v is a valid cookie domain-value.

func validCookieExpires

func validCookieExpires(t time.Time) bool

validCookieExpires reports whether v is a valid cookie expires-value.

func validCookiePathByte

func validCookiePathByte(b byte) bool

func validCookieValueByte

func validCookieValueByte(b byte) bool

func validMethod

func validMethod(method string) bool

func validNextProto

func validNextProto(proto string) bool

validNextProto reports whether the proto is not a blacklisted ALPN protocol name. Empty and built-in protocol types are blacklisted and can't be overridden with alternate implementations.

func valueOrDefault

func valueOrDefault(value, def string) string

Return value if nonempty, def otherwise.

func writeNotModified

func writeNotModified(w ResponseWriter)

func writeStatusLine

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.

type Client

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.

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 // Go 1.3
}

func (*Client) CloseIdleConnections 1.12

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.

func (*Client) Do

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 (*Client) Get

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 (*Client) Head

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 (*Client) Post

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 (*Client) PostForm

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 (*Client) checkRedirect

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

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

func (*Client) deadline

func (c *Client) deadline() time.Time

func (*Client) do

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

func (*Client) makeHeadersCopier

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 (*Client) send

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 (*Client) transport

func (c *Client) transport() RoundTripper

type CloseNotifier 1.1

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

type ConnState 1.3

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

type ConnState int
const (
    // StateNew represents a new connection that is expected to
    // send a request immediately. Connections begin at this
    // state and then transition to either StateActive or
    // StateClosed.
    StateNew ConnState = iota

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

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

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

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

func (ConnState) String 1.3

func (c ConnState) String() string

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

See https://tools.ietf.org/html/rfc6265 for details.

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 // Go 1.11
    Raw      string
    Unparsed []string // Raw text of unparsed attribute-value pairs
}

func readCookies

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 readSetCookies

func readSetCookies(h Header) []*Cookie

readSetCookies parses all "Set-Cookie" values from the header h and returns the successfully parsed Cookies.

func (*Cookie) String

func (c *Cookie) String() string

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

type CookieJar

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

type Dir

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

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

Note that Dir will allow access to files and directories starting with a period, which could expose sensitive directories like a .git directory or sensitive files like .htpasswd. To exclude files with a leading period, remove the files/directories from the server or create a custom FileSystem implementation.

An empty Dir is treated as ".".

type Dir string

func (Dir) Open

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 File

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 File interface {
    io.Closer
    io.Reader
    io.Seeker
    Readdir(count int) ([]os.FileInfo, error)
    Stat() (os.FileInfo, error)
}

type FileSystem

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

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

type Flusher

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 Flusher interface {
    // Flush sends any buffered data to the client.
    Flush()
}

type Handler

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.

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

func FileServer

func FileServer(root FileSystem) Handler

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

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

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

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

Example

Example (DotFileHiding)

Example (StripPrefix)

func NotFoundHandler

func NotFoundHandler() Handler

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

Example

func RedirectHandler

func RedirectHandler(url string, code int) Handler

RedirectHandler returns a request handler that redirects each request it receives to the given url using the given status code.

The provided code should be in the 3xx range and is usually StatusMovedPermanently, StatusFound or StatusSeeOther.

func StripPrefix

func StripPrefix(prefix string, h Handler) Handler

StripPrefix returns a handler that serves HTTP requests by removing the given prefix from the request URL's Path and invoking the handler h. StripPrefix handles a request for a path that doesn't begin with prefix by replying with an HTTP 404 not found error.

Example

func TimeoutHandler

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.

type HandlerFunc

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.

type HandlerFunc func(ResponseWriter, *Request)

func http2new400Handler

func http2new400Handler(err error) HandlerFunc

func (HandlerFunc) ServeHTTP

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

ServeHTTP calls f(w, r).

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

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

type Header map[string][]string

func cloneOrMakeHeader

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

func http2cloneHeader(h Header) Header

func (Header) Add

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 (Header) Clone 1.13

func (h Header) Clone() Header

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

func (Header) Del

func (h Header) Del(key string)

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

func (Header) Get

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 (Header) Set

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 (Header) Values 1.14

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 (Header) Write

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

Write writes a header in wire format.

func (Header) WriteSubset

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 (Header) get

func (h Header) get(key string) string

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

func (Header) has

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 (Header) sortedKeyValues

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 (Header) write

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

func (Header) writeSubset

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

type Hijacker

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

Example

type ProtocolError

ProtocolError represents an HTTP protocol error.

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

type ProtocolError struct {
    ErrorString string
}

func (*ProtocolError) Error

func (pe *ProtocolError) Error() string

type PushOptions 1.8

PushOptions describes options for Pusher.Push.

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
}

type Pusher 1.8

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 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
}
var _ Pusher = (*http2responseWriter)(nil)
var _ Pusher = (*timeoutWriter)(nil)

type Request

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.

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 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) // Go 1.8

    // 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 // Go 1.1

    // 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{} // Go 1.5

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

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

func (*Request) AddCookie

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

AddCookie adds a cookie to the request. Per RFC 6265 section 5.4, AddCookie does not attach more than one Cookie header field. That means all cookies, if any, are written into the same line, separated by semicolon.

func (*Request) BasicAuth 1.4

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

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

func (*Request) Clone 1.13

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

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

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

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

func (*Request) Cookies

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

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

func (*Request) FormFile

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

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

func (*Request) FormValue

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

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

func (*Request) MultipartReader

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

func (r *Request) ParseForm() error

ParseForm populates r.Form and r.PostForm.

For all requests, ParseForm parses the raw query from the URL and 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 (*Request) ParseMultipartForm

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

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

func (*Request) PostFormValue 1.1

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

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

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

func (*Request) Referer

func (r *Request) Referer() string

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

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

func (*Request) SetBasicAuth

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

func (r *Request) UserAgent() string

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

func (*Request) WithContext 1.7

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

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

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

func (r *Request) closeBody()

func (*Request) expectsContinue

func (r *Request) expectsContinue() bool

func (*Request) isH2Upgrade

func (r *Request) isH2Upgrade() bool

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

func (*Request) isReplayable

func (r *Request) isReplayable() bool

func (*Request) multipartReader

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

func (*Request) outgoingLength

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

func (r *Request) requiresHTTP1() bool

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

func (*Request) wantsClose

func (r *Request) wantsClose() bool

func (*Request) wantsHttp10KeepAlive

func (r *Request) wantsHttp10KeepAlive() bool

func (*Request) write

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

extraHeaders may be nil waitForContinue may be nil

type Response

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.

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 // Go 1.7

    // 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 // Go 1.3
}

func (*Response) Cookies

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

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

func (*Response) Location

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

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

func (*Response) ProtoAtLeast

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

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

func (*Response) Write

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 (*Response) bodyIsWritable

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 (*Response) closeBody

func (r *Response) closeBody()

func (*Response) isProtocolSwitch

func (r *Response) isProtocolSwitch() bool

isProtocolSwitch reports whether r is a response to a successful protocol upgrade.

type ResponseWriter

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

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

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

Example (Trailers)

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

type RoundTripper

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

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

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

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 DefaultTransport RoundTripper = &Transport{
    Proxy: ProxyFromEnvironment,
    DialContext: (&net.Dialer{
        Timeout:   30 * time.Second,
        KeepAlive: 30 * time.Second,
        DualStack: true,
    }).DialContext,
    ForceAttemptHTTP2:     true,
    MaxIdleConns:          100,
    IdleConnTimeout:       90 * time.Second,
    TLSHandshakeTimeout:   10 * time.Second,
    ExpectContinueTimeout: 1 * time.Second,
}

func NewFileTransport

func NewFileTransport(fs FileSystem) RoundTripper

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

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

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

type SameSite 1.11

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 SameSite int
const (
    SameSiteDefaultMode SameSite = iota + 1
    SameSiteLaxMode
    SameSiteStrictMode
    SameSiteNoneMode
)

type ServeMux

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.

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
}
var defaultServeMux ServeMux

func NewServeMux

func NewServeMux() *ServeMux

NewServeMux allocates and returns a new ServeMux.

func (*ServeMux) Handle

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

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

Example

func (*ServeMux) HandleFunc

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

HandleFunc registers the handler function for the given pattern.

func (*ServeMux) Handler 1.1

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

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

The path and host are used unchanged for CONNECT requests.

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

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

func (*ServeMux) ServeHTTP

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

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

func (*ServeMux) handler

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 (*ServeMux) match

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 (*ServeMux) redirectToPathSlash

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 (*ServeMux) shouldRedirectRLocked

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.

type Server

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

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 // Go 1.8

    // 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 // Go 1.8

    // 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) // Go 1.1

    // 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) // Go 1.3

    // 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 // Go 1.3

    // 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 // Go 1.13

    // 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 // Go 1.13

    disableKeepAlives int32     // accessed atomically.
    inShutdown        int32     // accessed atomically (non-zero means we're in Shutdown)
    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()
}

func (*Server) Close 1.8

func (srv *Server) Close() error

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

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

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

func (*Server) ListenAndServe

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 (*Server) ListenAndServeTLS

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 (*Server) RegisterOnShutdown 1.9

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 (*Server) Serve

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 (*Server) ServeTLS 1.9

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 (*Server) SetKeepAlivesEnabled 1.3

func (srv *Server) SetKeepAlivesEnabled(v bool)

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

func (*Server) Shutdown 1.8

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.

Example

func (*Server) closeDoneChanLocked

func (s *Server) closeDoneChanLocked()

func (*Server) closeIdleConns

func (s *Server) closeIdleConns() bool

closeIdleConns closes all idle connections and reports whether the server is quiescent.

func (*Server) closeListenersLocked

func (s *Server) closeListenersLocked() error

func (*Server) doKeepAlives

func (s *Server) doKeepAlives() bool

func (*Server) getDoneChan

func (s *Server) getDoneChan() <-chan struct{}

func (*Server) getDoneChanLocked

func (s *Server) getDoneChanLocked() chan struct{}

func (*Server) idleTimeout

func (s *Server) idleTimeout() time.Duration

func (*Server) initialReadLimitSize

func (srv *Server) initialReadLimitSize() int64

func (*Server) logf

func (s *Server) logf(format string, args ...interface{})

func (*Server) maxHeaderBytes

func (srv *Server) maxHeaderBytes() int

func (*Server) newConn

func (srv *Server) newConn(rwc net.Conn) *conn

Create new connection from rwc.

func (*Server) onceSetNextProtoDefaults

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 (*Server) onceSetNextProtoDefaults_Serve

func (srv *Server) onceSetNextProtoDefaults_Serve()

func (*Server) readHeaderTimeout

func (s *Server) readHeaderTimeout() time.Duration

func (*Server) setupHTTP2_Serve

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 (*Server) setupHTTP2_ServeTLS

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 (*Server) shouldConfigureHTTP2ForServe

func (srv *Server) shouldConfigureHTTP2ForServe() bool

shouldDoServeHTTP2 reports whether Server.Serve should configure automatic HTTP/2. (which sets up the srv.TLSNextProto map)

func (*Server) shuttingDown

func (s *Server) shuttingDown() bool

func (*Server) trackConn

func (s *Server) trackConn(c *conn, add bool)

func (*Server) trackListener

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

type Transport

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.

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[*Request]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) // Go 1.7

    // 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) // Go 1.14

    // 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) // Go 1.4

    // 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 // Go 1.3

    // 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 // Go 1.7

    // 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 // Go 1.11

    // 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 // Go 1.7

    // 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 // Go 1.1

    // 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 // Go 1.6

    // 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 // Go 1.6

    // ProxyConnectHeader optionally specifies headers to send to
    // proxies during CONNECT requests.
    ProxyConnectHeader Header // Go 1.8

    // 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 // Go 1.7

    // WriteBufferSize specifies the size of the write buffer used
    // when writing to the transport.
    // If zero, a default (currently 4KB) is used.
    WriteBufferSize int // Go 1.13

    // ReadBufferSize specifies the size of the read buffer used
    // when reading from the transport.
    // If zero, a default (currently 4KB) is used.
    ReadBufferSize int // Go 1.13

    // 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 // Go 1.13
}

func (*Transport) CancelRequest 1.1

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

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

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

func (*Transport) Clone 1.13

func (t *Transport) Clone() *Transport

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

func (*Transport) CloseIdleConnections

func (t *Transport) CloseIdleConnections()

CloseIdleConnections closes any connections which were previously connected from previous requests but are now sitting idle in a "keep-alive" state. It does not interrupt any connections currently in use.

func (*Transport) RegisterProtocol

func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper)

RegisterProtocol registers a new protocol with scheme. The Transport will pass requests using the given scheme to rt. It is rt's responsibility to simulate HTTP request semantics.

RegisterProtocol can be used by other packages to provide implementations of protocol schemes like "ftp" or "file".

If rt.RoundTrip returns ErrSkipAltProtocol, the Transport will handle the RoundTrip itself for that one request, as if the protocol were not registered.

func (*Transport) RoundTrip

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 (*Transport) alternateRoundTripper

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 (*Transport) cancelRequest

func (t *Transport) cancelRequest(req *Request, err error)

Cancel an in-flight request, recording the error value.

func (*Transport) connectMethodForRequest

func (t *Transport) connectMethodForRequest(treq *transportRequest) (cm connectMethod, err error)

func (*Transport) customDialTLS

func (t *Transport) customDialTLS(ctx context.Context, network, addr string) (conn net.Conn, err error)

func (*Transport) decConnsPerHost

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 (*Transport) dial

func (t *Transport) dial(ctx context.Context, network, addr string) (net.Conn, error)

func (*Transport) dialConn

func (t *Transport) dialConn(ctx context.Context, cm connectMethod) (pconn *persistConn, err error)

func (*Transport) dialConnFor

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 (*Transport) getConn

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 (*Transport) hasCustomTLSDialer

func (t *Transport) hasCustomTLSDialer() bool

func (*Transport) maxIdleConnsPerHost

func (t *Transport) maxIdleConnsPerHost() int

func (*Transport) onceSetNextProtoDefaults

func (t *Transport) onceSetNextProtoDefaults()

onceSetNextProtoDefaults initializes TLSNextProto. It must be called via t.nextProtoOnce.Do.

func (*Transport) putOrCloseIdleConn

func (t *Transport) putOrCloseIdleConn(pconn *persistConn)

func (*Transport) queueForDial

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 (*Transport) queueForIdleConn

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 (*Transport) readBufferSize

func (t *Transport) readBufferSize() int

func (*Transport) removeIdleConn

func (t *Transport) removeIdleConn(pconn *persistConn) bool

removeIdleConn marks pconn as dead.

func (*Transport) removeIdleConnLocked

func (t *Transport) removeIdleConnLocked(pconn *persistConn) bool

t.idleMu must be held.

func (*Transport) replaceReqCanceler

func (t *Transport) replaceReqCanceler(r *Request, 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 (*Transport) roundTrip

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

roundTrip implements a RoundTripper over HTTP.

func (*Transport) setReqCanceler

func (t *Transport) setReqCanceler(r *Request, fn func(error))

func (*Transport) tryPutIdleConn

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 (*Transport) useRegisteredProtocol

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 (*Transport) writeBufferSize

func (t *Transport) writeBufferSize() int

type atomicBool

type atomicBool int32

func (*atomicBool) isSet

func (b *atomicBool) isSet() bool

func (*atomicBool) setTrue

func (b *atomicBool) setTrue()

type badRequestError

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.

type badRequestError string

func (badRequestError) Error

func (e badRequestError) Error() string

type badStringError

type badStringError struct {
    what string
    str  string
}

func (*badStringError) Error

func (e *badStringError) Error() string

type body

body turns a Reader into a ReadCloser. Close ensures that the body has been fully read and then reads the trailer if necessary.

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
}

func (*body) Close

func (b *body) Close() error

func (*body) Read

func (b *body) Read(p []byte) (n int, err error)

func (*body) bodyRemains

func (b *body) bodyRemains() bool

bodyRemains reports whether future Read calls might yield data.

func (*body) didEarlyClose

func (b *body) didEarlyClose() bool

func (*body) readLocked

func (b *body) readLocked(p []byte) (n int, err error)

Must hold b.mu.

func (*body) readTrailer

func (b *body) readTrailer() error

func (*body) registerOnHitEOF

func (b *body) registerOnHitEOF(fn func())

func (*body) unreadDataSizeLocked

func (b *body) unreadDataSizeLocked() int64

unreadDataSizeLocked returns the number of bytes of unread input. It returns -1 if unknown. b.mu must be held.

type bodyEOFSignal

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.

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
}

func (*bodyEOFSignal) Close

func (es *bodyEOFSignal) Close() error

func (*bodyEOFSignal) Read

func (es *bodyEOFSignal) Read(p []byte) (n int, err error)

func (*bodyEOFSignal) condfn

func (es *bodyEOFSignal) condfn(err error) error

caller must hold es.mu.

type bodyLocked

bodyLocked is a io.Reader reading from a *body when its mutex is already held.

type bodyLocked struct {
    b *body
}

func (bodyLocked) Read

func (bl bodyLocked) Read(p []byte) (n int, err error)

type bufioFlushWriter

bufioFlushWriter is an io.Writer wrapper that flushes all writes on its wrapped writer if it's a *bufio.Writer.

type bufioFlushWriter struct{ w io.Writer }

func (bufioFlushWriter) Write

func (fw bufioFlushWriter) Write(p []byte) (n int, err error)

type byteReader

type byteReader struct {
    b    byte
    done bool
}

func (*byteReader) Read

func (br *byteReader) Read(p []byte) (n int, err error)

type cancelTimerBody

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.
type cancelTimerBody struct {
    stop          func() // stops the time.Timer waiting to cancel the request
    rc            io.ReadCloser
    reqDidTimeout func() bool
}

func (*cancelTimerBody) Close

func (b *cancelTimerBody) Close() error

func (*cancelTimerBody) Read

func (b *cancelTimerBody) Read(p []byte) (n int, err error)

type checkConnErrorWriter

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.

type checkConnErrorWriter struct {
    c *conn
}

func (checkConnErrorWriter) Write

func (w checkConnErrorWriter) Write(p []byte) (n int, err error)

type chunkWriter

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.

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
}

func (*chunkWriter) Write

func (cw *chunkWriter) Write(p []byte) (n int, err error)

func (*chunkWriter) close

func (cw *chunkWriter) close()

func (*chunkWriter) flush

func (cw *chunkWriter) flush()

func (*chunkWriter) writeHeader

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 closeWriter

type closeWriter interface {
    CloseWrite() error
}
var _ closeWriter = (*net.TCPConn)(nil)

type condResult

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

type condResult int
const (
    condNone condResult = iota
    condTrue
    condFalse
)

func checkIfMatch

func checkIfMatch(w ResponseWriter, r *Request) condResult

func checkIfModifiedSince

func checkIfModifiedSince(r *Request, modtime time.Time) condResult

func checkIfNoneMatch

func checkIfNoneMatch(w ResponseWriter, r *Request) condResult

func checkIfRange

func checkIfRange(w ResponseWriter, r *Request, modtime time.Time) condResult

func checkIfUnmodifiedSince

func checkIfUnmodifiedSince(r *Request, modtime time.Time) condResult

type conn

A conn represents the server side of an HTTP connection.

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
}

func (*conn) close

func (c *conn) close()

Close the connection.

func (*conn) closeWriteAndWait

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 (*conn) finalFlush

func (c *conn) finalFlush()

func (*conn) getState

func (c *conn) getState() (state ConnState, unixSec int64)

func (*conn) hijackLocked

func (c *conn) hijackLocked() (rwc net.Conn, buf *bufio.ReadWriter, err error)

c.mu must be held.

func (*conn) hijacked

func (c *conn) hijacked() bool

func (*conn) readRequest

func (c *conn) readRequest(ctx context.Context) (w *response, err error)

Read next request from connection.

func (*conn) serve

func (c *conn) serve(ctx context.Context)

Serve a new connection.

func (*conn) setState

func (c *conn) setState(nc net.Conn, state ConnState)

type connLRU

type connLRU struct {
    ll *list.List // list.Element.Value type is of *persistConn
    m  map[*persistConn]*list.Element
}

func (*connLRU) add

func (cl *connLRU) add(pc *persistConn)

add adds pc to the head of the linked list.

func (*connLRU) len

func (cl *connLRU) len() int

len returns the number of items in the cache.

func (*connLRU) remove

func (cl *connLRU) remove(pc *persistConn)

remove removes pc from cl.

func (*connLRU) removeOldest

func (cl *connLRU) removeOldest() *persistConn

type connReader

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.

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
}

func (*connReader) Read

func (cr *connReader) Read(p []byte) (n int, err error)

func (*connReader) abortPendingRead

func (cr *connReader) abortPendingRead()

func (*connReader) backgroundRead

func (cr *connReader) backgroundRead()

func (*connReader) closeNotify

func (cr *connReader) closeNotify()

may be called from multiple goroutines.

func (*connReader) handleReadError

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 (*connReader) hitReadLimit

func (cr *connReader) hitReadLimit() bool

func (*connReader) lock

func (cr *connReader) lock()

func (*connReader) setInfiniteReadLimit

func (cr *connReader) setInfiniteReadLimit()

func (*connReader) setReadLimit

func (cr *connReader) setReadLimit(remain int64)

func (*connReader) startBackgroundRead

func (cr *connReader) startBackgroundRead()

func (*connReader) unlock

func (cr *connReader) unlock()

type connectMethod

connectMethod is the map key (in its String form) for keeping persistent TCP connections alive for subsequent HTTP requests.

A connect method may be of the following types:

connectMethod.key().String()      Description
------------------------------    -------------------------
|http|foo.com                     http directly to server, no proxy
|https|foo.com                    https directly to server, no proxy
|https,h1|foo.com                 https directly to server w/o HTTP/2, no proxy
http://proxy.com|https|foo.com    http to proxy, then CONNECT to foo.com
http://proxy.com|http             http to proxy, http to anywhere after that
socks5://proxy.com|http|foo.com   socks5 to proxy, then http to foo.com
socks5://proxy.com|https|foo.com  socks5 to proxy, then https to foo.com
https://proxy.com|https|foo.com   https to proxy, then CONNECT to foo.com
https://proxy.com|http            https to proxy, http to anywhere after that
type connectMethod struct {
    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
}

func (*connectMethod) addr

func (cm *connectMethod) addr() string

addr returns the first hop "host:port" to which we need to TCP connect.

func (*connectMethod) key

func (cm *connectMethod) key() connectMethodKey

func (*connectMethod) proxyAuth

func (cm *connectMethod) proxyAuth() string

proxyAuth returns the Proxy-Authorization header to set on requests, if applicable.

func (*connectMethod) scheme

func (cm *connectMethod) scheme() string

scheme returns the first hop scheme: http, https, or socks5

func (*connectMethod) tlsHost

func (cm *connectMethod) tlsHost() string

tlsHost returns the host name to match against the peer's TLS certificate.

type connectMethodKey

connectMethodKey is the map key version of connectMethod, with a stringified proxy URL (or the empty string) instead of a pointer to a URL.

type connectMethodKey struct {
    proxy, scheme, addr string
    onlyH1              bool
}

func (connectMethodKey) String

func (k connectMethodKey) String() string

type contextKey

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

type contextKey struct {
    name string
}

func (*contextKey) String

func (k *contextKey) String() string

type countingWriter

countingWriter counts how many bytes have been written to it.

type countingWriter int64

func (*countingWriter) Write

func (w *countingWriter) Write(p []byte) (n int, err error)

type errorReader

type errorReader struct {
    err error
}

func (errorReader) Read

func (r errorReader) Read(p []byte) (n int, err error)

type exactSig

type exactSig struct {
    sig []byte
    ct  string
}

func (*exactSig) match

func (e *exactSig) match(data []byte, firstNonWS int) string

type expectContinueReader

wrapper around io.ReadCloser which on first read, sends an HTTP/1.1 100 Continue header

type expectContinueReader struct {
    resp       *response
    readCloser io.ReadCloser
    closed     bool
    sawEOF     bool
}

func (*expectContinueReader) Close

func (ecr *expectContinueReader) Close() error

func (*expectContinueReader) Read

func (ecr *expectContinueReader) Read(p []byte) (n int, err error)

type extraHeader

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.

type extraHeader struct {
    contentType      string
    connection       string
    transferEncoding string
    date             []byte // written if not nil
    contentLength    []byte // written if not nil
}

func (extraHeader) Write

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 fakeLocker

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.

type fakeLocker struct{}

func (fakeLocker) Lock

func (fakeLocker) Lock()

func (fakeLocker) Unlock

func (fakeLocker) Unlock()

type fileHandler

type fileHandler struct {
    root FileSystem
}

func (*fileHandler) ServeHTTP

func (f *fileHandler) ServeHTTP(w ResponseWriter, r *Request)

type fileTransport

fileTransport implements RoundTripper for the 'file' protocol.

type fileTransport struct {
    fh fileHandler
}

func (fileTransport) RoundTrip

func (t fileTransport) RoundTrip(req *Request) (resp *Response, err error)

type finishAsyncByteRead

finishAsyncByteRead finishes reading the 1-byte sniff from the ContentLength==0, Body!=nil case.

type finishAsyncByteRead struct {
    tw *transferWriter
}

func (finishAsyncByteRead) Read

func (fr finishAsyncByteRead) Read(p []byte) (n int, err error)

type globalOptionsHandler

globalOptionsHandler responds to "OPTIONS *" requests.

type globalOptionsHandler struct{}

func (globalOptionsHandler) ServeHTTP

func (globalOptionsHandler) ServeHTTP(w ResponseWriter, r *Request)

type gzipReader

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

type gzipReader struct {
    body *bodyEOFSignal // underlying HTTP/1 response body framing
    zr   *gzip.Reader   // lazily-initialized gzip reader
    zerr error          // any error from gzip.NewReader; sticky
}

func (*gzipReader) Close

func (gz *gzipReader) Close() error

func (*gzipReader) Read

func (gz *gzipReader) Read(p []byte) (n int, err error)

type h2Transport

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 h2Transport interface {
    CloseIdleConnections()
}

type headerSorter

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.

type headerSorter struct {
    kvs []keyValues
}

func (*headerSorter) Len

func (s *headerSorter) Len() int

func (*headerSorter) Less

func (s *headerSorter) Less(i, j int) bool

func (*headerSorter) Swap

func (s *headerSorter) Swap(i, j int)

type htmlSig

type htmlSig []byte

func (htmlSig) match

func (h htmlSig) match(data []byte, firstNonWS int) string

type http2ClientConn

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

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
}

func http2filterOutClientConn

func http2filterOutClientConn(in []*http2ClientConn, exclude *http2ClientConn) []*http2ClientConn

func (*http2ClientConn) CanTakeNewRequest

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 (*http2ClientConn) Close

func (cc *http2ClientConn) Close() error

Close closes the client connection immediately.

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

func (*http2ClientConn) Ping

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

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

func (*http2ClientConn) RoundTrip

func (cc *http2ClientConn) RoundTrip(req *Request) (*Response, error)

func (*http2ClientConn) Shutdown

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

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

func (*http2ClientConn) awaitOpenSlotForRequest

func (cc *http2ClientConn) awaitOpenSlotForRequest(req *Request) error

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

func (*http2ClientConn) canTakeNewRequestLocked

func (cc *http2ClientConn) canTakeNewRequestLocked() bool

func (*http2ClientConn) closeIfIdle

func (cc *http2ClientConn) closeIfIdle()

func (*http2ClientConn) encodeHeaders

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

requires cc.mu be held.

func (*http2ClientConn) encodeTrailers

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

requires cc.mu be held.

func (*http2ClientConn) forgetStreamID

func (cc *http2ClientConn) forgetStreamID(id uint32)

func (*http2ClientConn) frameScratchBuffer

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 (*http2ClientConn) idleState

func (cc *http2ClientConn) idleState() http2clientConnIdleState

func (*http2ClientConn) idleStateLocked

func (cc *http2ClientConn) idleStateLocked() (st http2clientConnIdleState)

func (*http2ClientConn) logf

func (cc *http2ClientConn) logf(format string, args ...interface{})

func (*http2ClientConn) newStream

func (cc *http2ClientConn) newStream() *http2clientStream

requires cc.mu be held.

func (*http2ClientConn) onIdleTimeout

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 (*http2ClientConn) putFrameScratchBuffer

func (cc *http2ClientConn) putFrameScratchBuffer(buf []byte)

func (*http2ClientConn) readLoop

func (cc *http2ClientConn) readLoop()

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

func (*http2ClientConn) responseHeaderTimeout

func (cc *http2ClientConn) responseHeaderTimeout() time.Duration

func (*http2ClientConn) roundTrip

func (cc *http2ClientConn) roundTrip(req *Request) (res *Response, gotErrAfterReqBodyWrite bool, err error)

func (*http2ClientConn) sendGoAway

func (cc *http2ClientConn) sendGoAway() error

func (*http2ClientConn) setGoAway

func (cc *http2ClientConn) setGoAway(f *http2GoAwayFrame)

func (*http2ClientConn) streamByID

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

func (*http2ClientConn) tooIdleLocked

func (cc *http2ClientConn) tooIdleLocked() bool

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

func (*http2ClientConn) vlogf

func (cc *http2ClientConn) vlogf(format string, args ...interface{})

func (*http2ClientConn) writeHeader

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

func (*http2ClientConn) writeHeaders

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

requires cc.wmu be held

func (*http2ClientConn) writeStreamReset

func (cc *http2ClientConn) writeStreamReset(streamID uint32, code http2ErrCode, err error)

type http2ClientConnPool

ClientConnPool manages a pool of HTTP/2 client connections.

type http2ClientConnPool interface {
    GetClientConn(req *Request, addr string) (*http2ClientConn, error)
    MarkDead(*http2ClientConn)
}

type http2ConnectionError

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

type http2ConnectionError http2ErrCode

func (http2ConnectionError) Error

func (e http2ConnectionError) Error() string

type http2ContinuationFrame

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

type http2ContinuationFrame struct {
    http2FrameHeader
    headerFragBuf []byte
}

func (http2ContinuationFrame) Header

func (h http2ContinuationFrame) Header() http2FrameHeader

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

func (*http2ContinuationFrame) HeaderBlockFragment

func (f *http2ContinuationFrame) HeaderBlockFragment() []byte

func (*http2ContinuationFrame) HeadersEnded

func (f *http2ContinuationFrame) HeadersEnded() bool

func (http2ContinuationFrame) String

func (h http2ContinuationFrame) String() string

func (*http2ContinuationFrame) checkValid

func (h *http2ContinuationFrame) checkValid()

func (*http2ContinuationFrame) invalidate

func (h *http2ContinuationFrame) invalidate()

func (http2ContinuationFrame) writeDebug

func (h http2ContinuationFrame) writeDebug(buf *bytes.Buffer)

type http2DataFrame

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

type http2DataFrame struct {
    http2FrameHeader
    data []byte
}

func (*http2DataFrame) Data

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.

func (http2DataFrame) Header

func (h http2DataFrame) Header() http2FrameHeader

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

func (*http2DataFrame) StreamEnded

func (f *http2DataFrame) StreamEnded() bool

func (http2DataFrame) String

func (h http2DataFrame) String() string

func (*http2DataFrame) checkValid

func (h *http2DataFrame) checkValid()

func (*http2DataFrame) invalidate

func (h *http2DataFrame) invalidate()

func (http2DataFrame) writeDebug

func (h http2DataFrame) writeDebug(buf *bytes.Buffer)

type http2ErrCode

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

type http2ErrCode uint32
const (
    http2ErrCodeNo                 http2ErrCode = 0x0
    http2ErrCodeProtocol           http2ErrCode = 0x1
    http2ErrCodeInternal           http2ErrCode = 0x2
    http2ErrCodeFlowControl        http2ErrCode = 0x3
    http2ErrCodeSettingsTimeout    http2ErrCode = 0x4
    http2ErrCodeStreamClosed       http2ErrCode = 0x5
    http2ErrCodeFrameSize          http2ErrCode = 0x6
    http2ErrCodeRefusedStream      http2ErrCode = 0x7
    http2ErrCodeCancel             http2ErrCode = 0x8
    http2ErrCodeCompression        http2ErrCode = 0x9
    http2ErrCodeConnect            http2ErrCode = 0xa
    http2ErrCodeEnhanceYourCalm    http2ErrCode = 0xb
    http2ErrCodeInadequateSecurity http2ErrCode = 0xc
    http2ErrCodeHTTP11Required     http2ErrCode = 0xd
)

func (http2ErrCode) String

func (e http2ErrCode) String() string

type http2Flags

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

type http2Flags uint8

Frame-specific FrameHeader flag bits.

const (
    // Data Frame
    http2FlagDataEndStream http2Flags = 0x1
    http2FlagDataPadded    http2Flags = 0x8

    // Headers Frame
    http2FlagHeadersEndStream  http2Flags = 0x1
    http2FlagHeadersEndHeaders http2Flags = 0x4
    http2FlagHeadersPadded     http2Flags = 0x8
    http2FlagHeadersPriority   http2Flags = 0x20

    // Settings Frame
    http2FlagSettingsAck http2Flags = 0x1

    // Ping Frame
    http2FlagPingAck http2Flags = 0x1

    // Continuation Frame
    http2FlagContinuationEndHeaders http2Flags = 0x4

    http2FlagPushPromiseEndHeaders http2Flags = 0x4
    http2FlagPushPromisePadded     http2Flags = 0x8
)

func (http2Flags) Has

func (f http2Flags) Has(v http2Flags) bool

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

type http2Frame

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.

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

type http2FrameHeader

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

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

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
}

func (http2FrameHeader) Header

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 (http2FrameHeader) String

func (h http2FrameHeader) String() string

func (*http2FrameHeader) checkValid

func (h *http2FrameHeader) checkValid()

func (*http2FrameHeader) invalidate

func (h *http2FrameHeader) invalidate()

func (http2FrameHeader) writeDebug

func (h http2FrameHeader) writeDebug(buf *bytes.Buffer)

type http2FrameType

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

type http2FrameType uint8
const (
    http2FrameData         http2FrameType = 0x0
    http2FrameHeaders      http2FrameType = 0x1
    http2FramePriority     http2FrameType = 0x2
    http2FrameRSTStream    http2FrameType = 0x3
    http2FrameSettings     http2FrameType = 0x4
    http2FramePushPromise  http2FrameType = 0x5
    http2FramePing         http2FrameType = 0x6
    http2FrameGoAway       http2FrameType = 0x7
    http2FrameWindowUpdate http2FrameType = 0x8
    http2FrameContinuation http2FrameType = 0x9
)

func (http2FrameType) String

func (t http2FrameType) String() string

type http2FrameWriteRequest

FrameWriteRequest is a request to write a frame.

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
}

func (http2FrameWriteRequest) Consume

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 (http2FrameWriteRequest) DataSize

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 (http2FrameWriteRequest) StreamID

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 (http2FrameWriteRequest) String

func (wr http2FrameWriteRequest) String() string

String is for debugging only.

func (http2FrameWriteRequest) isControl

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 (*http2FrameWriteRequest) replyToWriter

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 http2Framer

A Framer reads and writes Frames.

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

func http2NewFramer

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

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

func (*http2Framer) ErrorDetail

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 (*http2Framer) 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 (*http2Framer) SetMaxReadFrameSize

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 (*http2Framer) SetReuseFrames

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 (*http2Framer) WriteContinuation

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 (*http2Framer) WriteData

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 (*http2Framer) WriteDataPadded

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 (*http2Framer) WriteGoAway

func (f *http2Framer) WriteGoAway(maxStreamID uint32, code http2ErrCode, debugData []byte) error

func (*http2Framer) WriteHeaders

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 (*http2Framer) WritePing

func (f *http2Framer) WritePing(ack bool, data [8]byte) error

func (*http2Framer) WritePriority

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 (*http2Framer) WritePushPromise

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 (*http2Framer) WriteRSTStream

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 (*http2Framer) WriteRawFrame

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 (*http2Framer) WriteSettings

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 (*http2Framer) WriteSettingsAck

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 (*http2Framer) WriteWindowUpdate

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 (*http2Framer) checkFrameOrder

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 (*http2Framer) connError

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 (*http2Framer) endWrite

func (f *http2Framer) endWrite() error

func (*http2Framer) logWrite

func (f *http2Framer) logWrite()

func (*http2Framer) maxHeaderListSize

func (fr *http2Framer) maxHeaderListSize() uint32

func (*http2Framer) maxHeaderStringLen

func (fr *http2Framer) maxHeaderStringLen() int

func (*http2Framer) readMetaFrame

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.

func (*http2Framer) startWrite

func (f *http2Framer) startWrite(ftype http2FrameType, flags http2Flags, streamID uint32)

func (*http2Framer) writeByte

func (f *http2Framer) writeByte(v byte)

func (*http2Framer) writeBytes

func (f *http2Framer) writeBytes(v []byte)

func (*http2Framer) writeUint16

func (f *http2Framer) writeUint16(v uint16)

func (*http2Framer) writeUint32

func (f *http2Framer) writeUint32(v uint32)

type http2GoAwayError

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

type http2GoAwayError struct {
    LastStreamID uint32
    ErrCode      http2ErrCode
    DebugData    string
}

func (http2GoAwayError) Error

func (e http2GoAwayError) Error() string

type http2GoAwayFrame

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

type http2GoAwayFrame struct {
    http2FrameHeader
    LastStreamID uint32
    ErrCode      http2ErrCode
    debugData    []byte
}

func (*http2GoAwayFrame) DebugData

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.

func (http2GoAwayFrame) Header

func (h http2GoAwayFrame) Header() http2FrameHeader

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

func (http2GoAwayFrame) String

func (h http2GoAwayFrame) String() string

func (*http2GoAwayFrame) checkValid

func (h *http2GoAwayFrame) checkValid()

func (*http2GoAwayFrame) invalidate

func (h *http2GoAwayFrame) invalidate()

func (http2GoAwayFrame) writeDebug

func (h http2GoAwayFrame) writeDebug(buf *bytes.Buffer)

type http2HeadersFrame

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

type http2HeadersFrame struct {
    http2FrameHeader

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

    headerFragBuf []byte // not owned
}

func (*http2HeadersFrame) HasPriority

func (f *http2HeadersFrame) HasPriority() bool

func (http2HeadersFrame) Header

func (h http2HeadersFrame) Header() http2FrameHeader

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

func (*http2HeadersFrame) HeaderBlockFragment

func (f *http2HeadersFrame) HeaderBlockFragment() []byte

func (*http2HeadersFrame) HeadersEnded

func (f *http2HeadersFrame) HeadersEnded() bool

func (*http2HeadersFrame) StreamEnded

func (f *http2HeadersFrame) StreamEnded() bool

func (http2HeadersFrame) String

func (h http2HeadersFrame) String() string

func (*http2HeadersFrame) checkValid

func (h *http2HeadersFrame) checkValid()

func (*http2HeadersFrame) invalidate

func (h *http2HeadersFrame) invalidate()

func (http2HeadersFrame) writeDebug

func (h http2HeadersFrame) writeDebug(buf *bytes.Buffer)

type http2HeadersFrameParam

HeadersFrameParam are the parameters for writing a HEADERS frame.

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
}

type http2MetaHeadersFrame

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.

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
}

func (http2MetaHeadersFrame) HasPriority

func (f http2MetaHeadersFrame) HasPriority() bool

func (http2MetaHeadersFrame) Header

func (h http2MetaHeadersFrame) Header() http2FrameHeader

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

func (http2MetaHeadersFrame) HeaderBlockFragment

func (f http2MetaHeadersFrame) HeaderBlockFragment() []byte

func (http2MetaHeadersFrame) HeadersEnded

func (f http2MetaHeadersFrame) HeadersEnded() bool

func (*http2MetaHeadersFrame) PseudoFields

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

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

func (*http2MetaHeadersFrame) PseudoValue

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 (*http2MetaHeadersFrame) RegularFields

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 (http2MetaHeadersFrame) StreamEnded

func (f http2MetaHeadersFrame) StreamEnded() bool

func (http2MetaHeadersFrame) String

func (h http2MetaHeadersFrame) String() string

func (*http2MetaHeadersFrame) checkPseudos

func (mh *http2MetaHeadersFrame) checkPseudos() error

func (http2MetaHeadersFrame) checkValid

func (h http2MetaHeadersFrame) checkValid()

func (http2MetaHeadersFrame) invalidate

func (h http2MetaHeadersFrame) invalidate()

func (http2MetaHeadersFrame) writeDebug

func (h http2MetaHeadersFrame) writeDebug(buf *bytes.Buffer)

type http2OpenStreamOptions

OpenStreamOptions specifies extra options for WriteScheduler.OpenStream.

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
}

type http2PingFrame

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

type http2PingFrame struct {
    http2FrameHeader
    Data [8]byte
}

func (http2PingFrame) Header

func (h http2PingFrame) Header() http2FrameHeader

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

func (*http2PingFrame) IsAck

func (f *http2PingFrame) IsAck() bool

func (http2PingFrame) String

func (h http2PingFrame) String() string

func (*http2PingFrame) checkValid

func (h *http2PingFrame) checkValid()

func (*http2PingFrame) invalidate

func (h *http2PingFrame) invalidate()

func (http2PingFrame) writeDebug

func (h http2PingFrame) writeDebug(buf *bytes.Buffer)

type http2PriorityFrame

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

type http2PriorityFrame struct {
    http2FrameHeader
    http2PriorityParam
}

func (http2PriorityFrame) Header

func (h http2PriorityFrame) Header() http2FrameHeader

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

func (http2PriorityFrame) IsZero

func (p http2PriorityFrame) IsZero() bool

func (http2PriorityFrame) String

func (h http2PriorityFrame) String() string

func (*http2PriorityFrame) checkValid

func (h *http2PriorityFrame) checkValid()

func (*http2PriorityFrame) invalidate

func (h *http2PriorityFrame) invalidate()

func (http2PriorityFrame) writeDebug

func (h http2PriorityFrame) writeDebug(buf *bytes.Buffer)

type http2PriorityParam

PriorityParam are the stream prioritzation parameters.

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
}

func (http2PriorityParam) IsZero

func (p http2PriorityParam) IsZero() bool

type http2PriorityWriteSchedulerConfig

PriorityWriteSchedulerConfig configures a priorityWriteScheduler.

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
}

type http2PushPromiseFrame

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

type http2PushPromiseFrame struct {
    http2FrameHeader
    PromiseID     uint32
    headerFragBuf []byte // not owned
}

func (http2PushPromiseFrame) Header

func (h http2PushPromiseFrame) Header() http2FrameHeader

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

func (*http2PushPromiseFrame) HeaderBlockFragment

func (f *http2PushPromiseFrame) HeaderBlockFragment() []byte

func (*http2PushPromiseFrame) HeadersEnded

func (f *http2PushPromiseFrame) HeadersEnded() bool

func (http2PushPromiseFrame) String

func (h http2PushPromiseFrame) String() string

func (*http2PushPromiseFrame) checkValid

func (h *http2PushPromiseFrame) checkValid()

func (*http2PushPromiseFrame) invalidate

func (h *http2PushPromiseFrame) invalidate()

func (http2PushPromiseFrame) writeDebug

func (h http2PushPromiseFrame) writeDebug(buf *bytes.Buffer)

type http2PushPromiseParam

PushPromiseParam are the parameters for writing a PUSH_PROMISE frame.

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
}

type http2RSTStreamFrame

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

type http2RSTStreamFrame struct {
    http2FrameHeader
    ErrCode http2ErrCode
}

func (http2RSTStreamFrame) Header

func (h http2RSTStreamFrame) Header() http2FrameHeader

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

func (http2RSTStreamFrame) String

func (h http2RSTStreamFrame) String() string

func (*http2RSTStreamFrame) checkValid

func (h *http2RSTStreamFrame) checkValid()

func (*http2RSTStreamFrame) invalidate

func (h *http2RSTStreamFrame) invalidate()

func (http2RSTStreamFrame) writeDebug

func (h http2RSTStreamFrame) writeDebug(buf *bytes.Buffer)

type http2RoundTripOpt

RoundTripOpt are options for the Transport.RoundTripOpt method.

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
}

type http2ServeConnOpts

ServeConnOpts are options for the Server.ServeConn method.

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
}

func (*http2ServeConnOpts) baseConfig

func (o *http2ServeConnOpts) baseConfig() *Server

func (*http2ServeConnOpts) context

func (o *http2ServeConnOpts) context() context.Context

func (*http2ServeConnOpts) handler

func (o *http2ServeConnOpts) handler() Handler

type http2Server

Server is an HTTP/2 server.

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
}

func (*http2Server) ServeConn

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.

func (*http2Server) initialConnRecvWindowSize

func (s *http2Server) initialConnRecvWindowSize() int32

func (*http2Server) initialStreamRecvWindowSize

func (s *http2Server) initialStreamRecvWindowSize() int32

func (*http2Server) maxConcurrentStreams

func (s *http2Server) maxConcurrentStreams() uint32

func (*http2Server) maxQueuedControlFrames

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 (*http2Server) maxReadFrameSize

func (s *http2Server) maxReadFrameSize() uint32

type http2Setting

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

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
}

func (http2Setting) String

func (s http2Setting) String() string

func (http2Setting) Valid

func (s http2Setting) Valid() error

Valid reports whether the setting is valid.

type http2SettingID

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

type http2SettingID uint16
const (
    http2SettingHeaderTableSize      http2SettingID = 0x1
    http2SettingEnablePush           http2SettingID = 0x2
    http2SettingMaxConcurrentStreams http2SettingID = 0x3
    http2SettingInitialWindowSize    http2SettingID = 0x4
    http2SettingMaxFrameSize         http2SettingID = 0x5
    http2SettingMaxHeaderListSize    http2SettingID = 0x6
)

func (http2SettingID) String

func (s http2SettingID) String() string

type http2SettingsFrame

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

type http2SettingsFrame struct {
    http2FrameHeader
    p []byte
}

func (*http2SettingsFrame) ForeachSetting

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

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

func (*http2SettingsFrame) HasDuplicates

func (f *http2SettingsFrame) HasDuplicates() bool

HasDuplicates reports whether f contains any duplicate setting IDs.

func (http2SettingsFrame) Header

func (h http2SettingsFrame) Header() http2FrameHeader

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

func (*http2SettingsFrame) IsAck

func (f *http2SettingsFrame) IsAck() bool

func (*http2SettingsFrame) NumSettings

func (f *http2SettingsFrame) NumSettings() int

func (*http2SettingsFrame) Setting

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 (http2SettingsFrame) String

func (h http2SettingsFrame) String() string

func (*http2SettingsFrame) Value

func (f *http2SettingsFrame) Value(id http2SettingID) (v uint32, ok bool)

func (*http2SettingsFrame) checkValid

func (h *http2SettingsFrame) checkValid()

func (*http2SettingsFrame) invalidate

func (h *http2SettingsFrame) invalidate()

func (http2SettingsFrame) writeDebug

func (h http2SettingsFrame) writeDebug(buf *bytes.Buffer)

type http2StreamError

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

type http2StreamError struct {
    StreamID uint32
    Code     http2ErrCode
    Cause    error // optional additional detail
}

func http2streamError

func http2streamError(id uint32, code http2ErrCode) http2StreamError

func (http2StreamError) Error

func (e http2StreamError) Error() string

func (http2StreamError) staysWithinBuffer

func (se http2StreamError) staysWithinBuffer(max int) bool

func (http2StreamError) writeFrame

func (se http2StreamError) writeFrame(ctx http2writeContext) error

type http2Transport

Transport is an HTTP/2 Transport.

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

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

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

func (*http2Transport) CloseIdleConnections

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 (*http2Transport) NewClientConn

func (t *http2Transport) NewClientConn(c net.Conn) (*http2ClientConn, error)

func (*http2Transport) RoundTrip

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

func (*http2Transport) RoundTripOpt

func (t *http2Transport) RoundTripOpt(req *Request, opt http2RoundTripOpt) (*Response, error)

RoundTripOpt is like RoundTrip, but takes options.

func (*http2Transport) connPool

func (t *http2Transport) connPool() http2ClientConnPool

func (*http2Transport) dialClientConn

func (t *http2Transport) dialClientConn(addr string, singleUse bool) (*http2ClientConn, error)

func (*http2Transport) dialTLS

func (t *http2Transport) dialTLS() func(string, string, *tls.Config) (net.Conn, error)

func (*http2Transport) dialTLSDefault

func (t *http2Transport) dialTLSDefault(network, addr string, cfg *tls.Config) (net.Conn, error)

func (*http2Transport) disableCompression

func (t *http2Transport) disableCompression() bool

func (*http2Transport) disableKeepAlives

func (t *http2Transport) disableKeepAlives() bool

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

func (*http2Transport) expectContinueTimeout

func (t *http2Transport) expectContinueTimeout() time.Duration

func (*http2Transport) getBodyWriterState

func (t *http2Transport) getBodyWriterState(cs *http2clientStream, body io.Reader) (s http2bodyWriterState)

func (*http2Transport) idleConnTimeout

func (t *http2Transport) idleConnTimeout() time.Duration

func (*http2Transport) initConnPool

func (t *http2Transport) initConnPool()

func (*http2Transport) logf

func (t *http2Transport) logf(format string, args ...interface{})

func (*http2Transport) maxHeaderListSize

func (t *http2Transport) maxHeaderListSize() uint32

func (*http2Transport) newClientConn

func (t *http2Transport) newClientConn(c net.Conn, singleUse bool) (*http2ClientConn, error)

func (*http2Transport) newTLSConfig

func (t *http2Transport) newTLSConfig(host string) *tls.Config

func (*http2Transport) vlogf

func (t *http2Transport) vlogf(format string, args ...interface{})

type http2UnknownFrame

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

type http2UnknownFrame struct {
    http2FrameHeader
    p []byte
}

func (http2UnknownFrame) Header

func (h http2UnknownFrame) Header() http2FrameHeader

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

func (*http2UnknownFrame) Payload

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.

func (http2UnknownFrame) String

func (h http2UnknownFrame) String() string

func (*http2UnknownFrame) checkValid

func (h *http2UnknownFrame) checkValid()

func (*http2UnknownFrame) invalidate

func (h *http2UnknownFrame) invalidate()

func (http2UnknownFrame) writeDebug

func (h http2UnknownFrame) writeDebug(buf *bytes.Buffer)

type http2WindowUpdateFrame

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

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

func (http2WindowUpdateFrame) Header

func (h http2WindowUpdateFrame) Header() http2FrameHeader

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

func (http2WindowUpdateFrame) String

func (h http2WindowUpdateFrame) String() string

func (*http2WindowUpdateFrame) checkValid

func (h *http2WindowUpdateFrame) checkValid()

func (*http2WindowUpdateFrame) invalidate

func (h *http2WindowUpdateFrame) invalidate()

func (http2WindowUpdateFrame) writeDebug

func (h http2WindowUpdateFrame) writeDebug(buf *bytes.Buffer)

type http2WriteScheduler

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

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

func http2NewPriorityWriteScheduler

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

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 http2addConnCall

type http2addConnCall struct {
    p    *http2clientConnPool
    done chan struct{} // closed when done
    err  error
}

func (*http2addConnCall) run

func (c *http2addConnCall) run(t *http2Transport, key string, tc *tls.Conn)

type http2badStringError

type http2badStringError struct {
    what string
    str  string
}

func (*http2badStringError) Error

func (e *http2badStringError) Error() string

type http2bodyReadMsg

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

type http2bodyReadMsg struct {
    st *http2stream
    n  int
}

type http2bodyWriterState

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

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
}

func (http2bodyWriterState) cancel

func (s http2bodyWriterState) cancel()

func (http2bodyWriterState) on100

func (s http2bodyWriterState) on100()

func (http2bodyWriterState) scheduleBodyWrite

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 http2bufferedWriter

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.

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

func http2newBufferedWriter

func http2newBufferedWriter(w io.Writer) *http2bufferedWriter

func (*http2bufferedWriter) Available

func (w *http2bufferedWriter) Available() int

func (*http2bufferedWriter) Flush

func (w *http2bufferedWriter) Flush() error

func (*http2bufferedWriter) Write

func (w *http2bufferedWriter) Write(p []byte) (n int, err error)

type http2chunkWriter

type http2chunkWriter struct{ rws *http2responseWriterState }

func (http2chunkWriter) Write

func (cw http2chunkWriter) Write(p []byte) (n int, err error)

type http2clientConnIdleState

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

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

type http2clientConnPool

TODO: use singleflight for dialing and addConnCalls?

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
}

func (*http2clientConnPool) GetClientConn

func (p *http2clientConnPool) GetClientConn(req *Request, addr string) (*http2ClientConn, error)

func (*http2clientConnPool) MarkDead

func (p *http2clientConnPool) MarkDead(cc *http2ClientConn)

func (*http2clientConnPool) addConn

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

func (*http2clientConnPool) addConnIfNeeded

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 (*http2clientConnPool) addConnLocked

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

p.mu must be held

func (*http2clientConnPool) closeIdleConnections

func (p *http2clientConnPool) closeIdleConnections()

func (*http2clientConnPool) getClientConn

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

func (*http2clientConnPool) getStartDialLocked

func (p *http2clientConnPool) getStartDialLocked(addr string) *http2dialCall

requires p.mu is held.

func (*http2clientConnPool) shouldTraceGetConn

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.

type http2clientConnPoolIdleCloser

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

type http2clientConnPoolIdleCloser interface {
    http2ClientConnPool
    closeIdleConnections()
}
var (
    _ http2clientConnPoolIdleCloser = (*http2clientConnPool)(nil)
    _ http2clientConnPoolIdleCloser = http2noDialClientConnPool{}
)

type http2clientConnReadLoop

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

type http2clientConnReadLoop struct {
    cc            *http2ClientConn
    closeWhenIdle bool
}

func (*http2clientConnReadLoop) cleanup

func (rl *http2clientConnReadLoop) cleanup()

func (*http2clientConnReadLoop) endStream

func (rl *http2clientConnReadLoop) endStream(cs *http2clientStream)

func (*http2clientConnReadLoop) endStreamError

func (rl *http2clientConnReadLoop) endStreamError(cs *http2clientStream, err error)

func (*http2clientConnReadLoop) handleResponse

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 (*http2clientConnReadLoop) processData

func (rl *http2clientConnReadLoop) processData(f *http2DataFrame) error

func (*http2clientConnReadLoop) processGoAway

func (rl *http2clientConnReadLoop) processGoAway(f *http2GoAwayFrame) error

func (*http2clientConnReadLoop) processHeaders

func (rl *http2clientConnReadLoop) processHeaders(f *http2MetaHeadersFrame) error

func (*http2clientConnReadLoop) processPing

func (rl *http2clientConnReadLoop) processPing(f *http2PingFrame) error

func (*http2clientConnReadLoop) processPushPromise

func (rl *http2clientConnReadLoop) processPushPromise(f *http2PushPromiseFrame) error

func (*http2clientConnReadLoop) processResetStream

func (rl *http2clientConnReadLoop) processResetStream(f *http2RSTStreamFrame) error

func (*http2clientConnReadLoop) processSettings

func (rl *http2clientConnReadLoop) processSettings(f *http2SettingsFrame) error

func (*http2clientConnReadLoop) processTrailers

func (rl *http2clientConnReadLoop) processTrailers(cs *http2clientStream, f *http2MetaHeadersFrame) error

func (*http2clientConnReadLoop) processWindowUpdate

func (rl *http2clientConnReadLoop) processWindowUpdate(f *http2WindowUpdateFrame) error

func (*http2clientConnReadLoop) run

func (rl *http2clientConnReadLoop) run() error

type http2clientStream

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

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
}

func (*http2clientStream) abortRequestBodyWrite

func (cs *http2clientStream) abortRequestBodyWrite(err error)

func (*http2clientStream) awaitFlowControl

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 (*http2clientStream) awaitRequestCancel

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 (*http2clientStream) cancelStream

func (cs *http2clientStream) cancelStream()

func (*http2clientStream) checkResetOrDone

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 (*http2clientStream) copyTrailers

func (cs *http2clientStream) copyTrailers()

func (*http2clientStream) get1xxTraceFunc

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 (*http2clientStream) getStartedWrite

func (cs *http2clientStream) getStartedWrite() bool

func (*http2clientStream) writeRequestBody

func (cs *http2clientStream) writeRequestBody(body io.Reader, bodyCloser io.Closer) (err error)

type http2closeWaiter

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

type http2closeWaiter chan struct{}

func (http2closeWaiter) Close

func (cw http2closeWaiter) Close()

Close marks the closeWaiter as closed and unblocks any waiters.

func (*http2closeWaiter) Init

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 (http2closeWaiter) Wait

func (cw http2closeWaiter) Wait()

Wait waits for the closeWaiter to become closed.

type http2connError

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.

type http2connError struct {
    Code   http2ErrCode // the ConnectionError error code
    Reason string       // additional reason
}

func (http2connError) Error

func (e http2connError) Error() string

type http2connectionStater

type http2connectionStater interface {
    ConnectionState() tls.ConnectionState
}

type http2dataBuffer

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.

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

func (*http2dataBuffer) Len

func (b *http2dataBuffer) Len() int

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

func (*http2dataBuffer) Read

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 (*http2dataBuffer) Write

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

Write appends p to the buffer.

func (*http2dataBuffer) bytesFromFirstChunk

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

func (*http2dataBuffer) lastChunkOrAlloc

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

type http2dialCall

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

type http2dialCall struct {
    p    *http2clientConnPool
    done chan struct{}    // closed when done
    res  *http2ClientConn // valid after done is closed
    err  error            // valid after done is closed
}

func (*http2dialCall) dial

func (c *http2dialCall) dial(addr string)

run in its own goroutine.

type http2duplicatePseudoHeaderError

type http2duplicatePseudoHeaderError string

func (http2duplicatePseudoHeaderError) Error

func (e http2duplicatePseudoHeaderError) Error() string

type http2erringRoundTripper

type http2erringRoundTripper struct{ err error }

func (http2erringRoundTripper) RoundTrip

func (rt http2erringRoundTripper) RoundTrip(*Request) (*Response, error)

type http2errorReader

type http2errorReader struct{ err error }

func (http2errorReader) Read

func (r http2errorReader) Read(p []byte) (int, error)

type http2flow

flow is the flow control window's size.

type http2flow struct {
    // 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
}

func (*http2flow) add

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.

func (*http2flow) available

func (f *http2flow) available() int32

func (*http2flow) setConnFlow

func (f *http2flow) setConnFlow(cf *http2flow)

func (*http2flow) take

func (f *http2flow) take(n int32)

type http2flushFrameWriter

type http2flushFrameWriter struct{}

func (http2flushFrameWriter) staysWithinBuffer

func (http2flushFrameWriter) staysWithinBuffer(max int) bool

func (http2flushFrameWriter) writeFrame

func (http2flushFrameWriter) writeFrame(ctx http2writeContext) error

type http2frameCache

type http2frameCache struct {
    dataFrame http2DataFrame
}

func (*http2frameCache) getDataFrame

func (fc *http2frameCache) getDataFrame() *http2DataFrame

type http2frameParser

a frameParser parses a frame given its FrameHeader and payload bytes. The length of payload will always equal fh.Length (which might be 0).

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

func http2typeFrameParser

func http2typeFrameParser(t http2FrameType) http2frameParser

type http2frameWriteResult

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

type http2frameWriteResult struct {
    wr  http2FrameWriteRequest // what was written (or attempted)
    err error                  // result of the writeFrame call
}

type http2gate

A gate lets two goroutines coordinate their activities.

type http2gate chan struct{}

func (http2gate) Done

func (g http2gate) Done()

func (http2gate) Wait

func (g http2gate) Wait()

type http2goAwayFlowError

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

type http2goAwayFlowError struct{}

func (http2goAwayFlowError) Error

func (http2goAwayFlowError) Error() string

type http2goroutineLock

type http2goroutineLock uint64

func http2newGoroutineLock

func http2newGoroutineLock() http2goroutineLock

func (http2goroutineLock) check

func (g http2goroutineLock) check()

func (http2goroutineLock) checkNotOn

func (g http2goroutineLock) checkNotOn()

type http2gzipReader

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

type http2gzipReader struct {
    body io.ReadCloser // underlying Response.Body
    zr   *gzip.Reader  // lazily-initialized gzip reader
    zerr error         // sticky error
}

func (*http2gzipReader) Close

func (gz *http2gzipReader) Close() error

func (*http2gzipReader) Read

func (gz *http2gzipReader) Read(p []byte) (n int, err error)

type http2handlerPanicRST

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

type http2handlerPanicRST struct {
    StreamID uint32
}

func (http2handlerPanicRST) staysWithinBuffer

func (hp http2handlerPanicRST) staysWithinBuffer(max int) bool

func (http2handlerPanicRST) writeFrame

func (hp http2handlerPanicRST) writeFrame(ctx http2writeContext) error

type http2headerFieldNameError

type http2headerFieldNameError string

func (http2headerFieldNameError) Error

func (e http2headerFieldNameError) Error() string

type http2headerFieldValueError

type http2headerFieldValueError string

func (http2headerFieldValueError) Error

func (e http2headerFieldValueError) Error() string

type http2headersEnder

type http2headersEnder interface {
    HeadersEnded() bool
}

type http2headersOrContinuation

type http2headersOrContinuation interface {
    http2headersEnder
    HeaderBlockFragment() []byte
}

type http2httpError

type http2httpError struct {
    msg     string
    timeout bool
}

func (*http2httpError) Error

func (e *http2httpError) Error() string

func (*http2httpError) Temporary

func (e *http2httpError) Temporary() bool

func (*http2httpError) Timeout

func (e *http2httpError) Timeout() bool

type http2noCachedConnError

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.

type http2noCachedConnError struct{}

func (http2noCachedConnError) Error

func (http2noCachedConnError) Error() string

func (http2noCachedConnError) IsHTTP2NoCachedConnError

func (http2noCachedConnError) IsHTTP2NoCachedConnError()

type http2noDialClientConnPool

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

type http2noDialClientConnPool struct{ *http2clientConnPool }

func (http2noDialClientConnPool) GetClientConn

func (p http2noDialClientConnPool) GetClientConn(req *Request, addr string) (*http2ClientConn, error)

func (http2noDialClientConnPool) MarkDead

func (p http2noDialClientConnPool) MarkDead(cc *http2ClientConn)

func (http2noDialClientConnPool) addConn

func (p http2noDialClientConnPool) addConn(key string, cc *http2ClientConn)

func (http2noDialClientConnPool) addConnIfNeeded

func (p http2noDialClientConnPool) 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 (http2noDialClientConnPool) addConnLocked

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

p.mu must be held

func (http2noDialClientConnPool) closeIdleConnections

func (p http2noDialClientConnPool) closeIdleConnections()

func (http2noDialClientConnPool) getClientConn

func (p http2noDialClientConnPool) getClientConn(req *Request, addr string, dialOnMiss bool) (*http2ClientConn, error)

func (http2noDialClientConnPool) getStartDialLocked

func (p http2noDialClientConnPool) getStartDialLocked(addr string) *http2dialCall

requires p.mu is held.

func (http2noDialClientConnPool) shouldTraceGetConn

func (p http2noDialClientConnPool) 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.

type http2noDialH2RoundTripper

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)

type http2noDialH2RoundTripper struct{ *http2Transport }

func (http2noDialH2RoundTripper) CloseIdleConnections

func (t http2noDialH2RoundTripper) 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 (http2noDialH2RoundTripper) NewClientConn

func (t http2noDialH2RoundTripper) NewClientConn(c net.Conn) (*http2ClientConn, error)

func (http2noDialH2RoundTripper) RoundTrip

func (rt http2noDialH2RoundTripper) RoundTrip(req *Request) (*Response, error)

func (http2noDialH2RoundTripper) RoundTripOpt

func (t http2noDialH2RoundTripper) RoundTripOpt(req *Request, opt http2RoundTripOpt) (*Response, error)

RoundTripOpt is like RoundTrip, but takes options.

func (http2noDialH2RoundTripper) connPool

func (t http2noDialH2RoundTripper) connPool() http2ClientConnPool

func (http2noDialH2RoundTripper) dialClientConn

func (t http2noDialH2RoundTripper) dialClientConn(addr string, singleUse bool) (*http2ClientConn, error)

func (http2noDialH2RoundTripper) dialTLS

func (t http2noDialH2RoundTripper) dialTLS() func(string, string, *tls.Config) (net.Conn, error)

func (http2noDialH2RoundTripper) dialTLSDefault

func (t http2noDialH2RoundTripper) dialTLSDefault(network, addr string, cfg *tls.Config) (net.Conn, error)

func (http2noDialH2RoundTripper) disableCompression

func (t http2noDialH2RoundTripper) disableCompression() bool

func (http2noDialH2RoundTripper) disableKeepAlives

func (t http2noDialH2RoundTripper) disableKeepAlives() bool

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

func (http2noDialH2RoundTripper) expectContinueTimeout

func (t http2noDialH2RoundTripper) expectContinueTimeout() time.Duration

func (http2noDialH2RoundTripper) getBodyWriterState

func (t http2noDialH2RoundTripper) getBodyWriterState(cs *http2clientStream, body io.Reader) (s http2bodyWriterState)

func (http2noDialH2RoundTripper) idleConnTimeout

func (t http2noDialH2RoundTripper) idleConnTimeout() time.Duration

func (http2noDialH2RoundTripper) initConnPool

func (t http2noDialH2RoundTripper) initConnPool()

func (http2noDialH2RoundTripper) logf

func (t http2noDialH2RoundTripper) logf(format string, args ...interface{})

func (http2noDialH2RoundTripper) maxHeaderListSize

func (t http2noDialH2RoundTripper) maxHeaderListSize() uint32

func (http2noDialH2RoundTripper) newClientConn

func (t http2noDialH2RoundTripper) newClientConn(c net.Conn, singleUse bool) (*http2ClientConn, error)

func (http2noDialH2RoundTripper) newTLSConfig

func (t http2noDialH2RoundTripper) newTLSConfig(host string) *tls.Config

func (http2noDialH2RoundTripper) vlogf

func (t http2noDialH2RoundTripper) vlogf(format string, args ...interface{})

type http2pipe

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)

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
}

func (*http2pipe) BreakWithError

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 (*http2pipe) CloseWithError

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 (*http2pipe) Done

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

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

func (*http2pipe) Err

func (p *http2pipe) Err() error

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

func (*http2pipe) Len

func (p *http2pipe) Len() int

func (*http2pipe) Read

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 (*http2pipe) Write

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 (*http2pipe) closeDoneLocked

func (p *http2pipe) closeDoneLocked()

requires p.mu be held.

func (*http2pipe) closeWithError

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

func (*http2pipe) closeWithErrorAndCode

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.

type http2pipeBuffer

type http2pipeBuffer interface {
    Len() int
    io.Writer
    io.Reader
}

type http2priorityNode

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.

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
}

func (*http2priorityNode) addBytes

func (n *http2priorityNode) addBytes(b int64)

func (*http2priorityNode) setParent

func (n *http2priorityNode) setParent(parent *http2priorityNode)

func (*http2priorityNode) walkReadyInOrder

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 http2priorityNodeState

type http2priorityNodeState int
const (
    http2priorityNodeOpen http2priorityNodeState = iota
    http2priorityNodeClosed
    http2priorityNodeIdle
)

type http2priorityWriteScheduler

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 (*http2priorityWriteScheduler) AdjustStream

func (ws *http2priorityWriteScheduler) AdjustStream(streamID uint32, priority http2PriorityParam)

func (*http2priorityWriteScheduler) CloseStream

func (ws *http2priorityWriteScheduler) CloseStream(streamID uint32)

func (*http2priorityWriteScheduler) OpenStream

func (ws *http2priorityWriteScheduler) OpenStream(streamID uint32, options http2OpenStreamOptions)

func (*http2priorityWriteScheduler) Pop

func (ws *http2priorityWriteScheduler) Pop() (wr http2FrameWriteRequest, ok bool)

func (*http2priorityWriteScheduler) Push

func (ws *http2priorityWriteScheduler) Push(wr http2FrameWriteRequest)

func (*http2priorityWriteScheduler) addClosedOrIdleNode

func (ws *http2priorityWriteScheduler) addClosedOrIdleNode(list *[]*http2priorityNode, maxSize int, n *http2priorityNode)

func (*http2priorityWriteScheduler) removeNode

func (ws *http2priorityWriteScheduler) removeNode(n *http2priorityNode)

type http2pseudoHeaderError

type http2pseudoHeaderError string

func (http2pseudoHeaderError) Error

func (e http2pseudoHeaderError) Error() string

type http2randomWriteScheduler

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 (*http2randomWriteScheduler) AdjustStream

func (ws *http2randomWriteScheduler) AdjustStream(streamID uint32, priority http2PriorityParam)

func (*http2randomWriteScheduler) CloseStream

func (ws *http2randomWriteScheduler) CloseStream(streamID uint32)

func (*http2randomWriteScheduler) OpenStream

func (ws *http2randomWriteScheduler) OpenStream(streamID uint32, options http2OpenStreamOptions)

func (*http2randomWriteScheduler) Pop

func (ws *http2randomWriteScheduler) Pop() (http2FrameWriteRequest, bool)

func (*http2randomWriteScheduler) Push

func (ws *http2randomWriteScheduler) Push(wr http2FrameWriteRequest)

type http2readFrameResult

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 http2requestBody

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

type http2requestBody struct {
    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
}

func (*http2requestBody) Close

func (b *http2requestBody) Close() error

func (*http2requestBody) Read

func (b *http2requestBody) Read(p []byte) (n int, err error)

type http2requestParam

type http2requestParam struct {
    method                  string
    scheme, authority, path string
    header                  Header
}

type http2resAndError

type http2resAndError struct {
    res *Response
    err error
}

type http2responseWriter

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.

type http2responseWriter struct {
    rws *http2responseWriterState
}

func (*http2responseWriter) CloseNotify

func (w *http2responseWriter) CloseNotify() <-chan bool

func (*http2responseWriter) Flush

func (w *http2responseWriter) Flush()

func (*http2responseWriter) Header

func (w *http2responseWriter) Header() Header

func (*http2responseWriter) Push

func (w *http2responseWriter) Push(target string, opts *PushOptions) error

func (*http2responseWriter) Write

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 (*http2responseWriter) WriteHeader

func (w *http2responseWriter) WriteHeader(code int)

func (*http2responseWriter) WriteString

func (w *http2responseWriter) WriteString(s string) (n int, err error)

func (*http2responseWriter) handlerDone

func (w *http2responseWriter) handlerDone()

func (*http2responseWriter) write

func (w *http2responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error)

either dataB or dataS is non-zero.

type http2responseWriterState

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 (*http2responseWriterState) declareTrailer

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 (*http2responseWriterState) hasNonemptyTrailers

func (rws *http2responseWriterState) hasNonemptyTrailers() bool

func (*http2responseWriterState) hasTrailers

func (rws *http2responseWriterState) hasTrailers() bool

func (*http2responseWriterState) promoteUndeclaredTrailers

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 (*http2responseWriterState) writeChunk

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 (*http2responseWriterState) writeHeader

func (rws *http2responseWriterState) writeHeader(code int)

type http2serverConn

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 (*http2serverConn) CloseConn

func (sc *http2serverConn) CloseConn() error

func (*http2serverConn) Flush

func (sc *http2serverConn) Flush() error

func (*http2serverConn) Framer

func (sc *http2serverConn) Framer() *http2Framer

func (*http2serverConn) HeaderEncoder

func (sc *http2serverConn) HeaderEncoder() (*hpack.Encoder, *bytes.Buffer)

func (*http2serverConn) awaitGracefulShutdown

func (sc *http2serverConn) awaitGracefulShutdown(sharedCh <-chan struct{}, privateCh chan struct{})

func (*http2serverConn) canonicalHeader

func (sc *http2serverConn) canonicalHeader(v string) string

func (*http2serverConn) closeAllStreamsOnConnClose

func (sc *http2serverConn) closeAllStreamsOnConnClose()

func (*http2serverConn) closeStream

func (sc *http2serverConn) closeStream(st *http2stream, err error)

func (*http2serverConn) condlogf

func (sc *http2serverConn) condlogf(err error, format string, args ...interface{})

func (*http2serverConn) curOpenStreams

func (sc *http2serverConn) curOpenStreams() uint32

func (*http2serverConn) goAway

func (sc *http2serverConn) goAway(code http2ErrCode)

func (*http2serverConn) logf

func (sc *http2serverConn) logf(format string, args ...interface{})

func (*http2serverConn) maxHeaderListSize

func (sc *http2serverConn) maxHeaderListSize() uint32

func (*http2serverConn) newStream

func (sc *http2serverConn) newStream(id, pusherID uint32, state http2streamState) *http2stream

func (*http2serverConn) newWriterAndRequest

func (sc *http2serverConn) newWriterAndRequest(st *http2stream, f *http2MetaHeadersFrame) (*http2responseWriter, *Request, error)

func (*http2serverConn) newWriterAndRequestNoBody

func (sc *http2serverConn) newWriterAndRequestNoBody(st *http2stream, rp http2requestParam) (*http2responseWriter, *Request, error)

func (*http2serverConn) noteBodyRead

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

func (*http2serverConn) noteBodyReadFromHandler

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 (*http2serverConn) notePanic

func (sc *http2serverConn) notePanic()

func (*http2serverConn) onIdleTimer

func (sc *http2serverConn) onIdleTimer()

func (*http2serverConn) onSettingsTimer

func (sc *http2serverConn) onSettingsTimer()

func (*http2serverConn) onShutdownTimer

func (sc *http2serverConn) onShutdownTimer()

func (*http2serverConn) processData

func (sc *http2serverConn) processData(f *http2DataFrame) error

func (*http2serverConn) processFrame

func (sc *http2serverConn) processFrame(f http2Frame) error

func (*http2serverConn) processFrameFromReader

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 (*http2serverConn) processGoAway

func (sc *http2serverConn) processGoAway(f *http2GoAwayFrame) error

func (*http2serverConn) processHeaders

func (sc *http2serverConn) processHeaders(f *http2MetaHeadersFrame) error

func (*http2serverConn) processPing

func (sc *http2serverConn) processPing(f *http2PingFrame) error

func (*http2serverConn) processPriority

func (sc *http2serverConn) processPriority(f *http2PriorityFrame) error

func (*http2serverConn) processResetStream

func (sc *http2serverConn) processResetStream(f *http2RSTStreamFrame) error

func (*http2serverConn) processSetting

func (sc *http2serverConn) processSetting(s http2Setting) error

func (*http2serverConn) processSettingInitialWindowSize

func (sc *http2serverConn) processSettingInitialWindowSize(val uint32) error

func (*http2serverConn) processSettings

func (sc *http2serverConn) processSettings(f *http2SettingsFrame) error

func (*http2serverConn) processWindowUpdate

func (sc *http2serverConn) processWindowUpdate(f *http2WindowUpdateFrame) error

func (*http2serverConn) readFrames

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 (*http2serverConn) readPreface

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 (*http2serverConn) rejectConn

func (sc *http2serverConn) rejectConn(err http2ErrCode, debug string)

func (*http2serverConn) resetStream

func (sc *http2serverConn) resetStream(se http2StreamError)

func (*http2serverConn) runHandler

func (sc *http2serverConn) runHandler(rw *http2responseWriter, req *Request, handler func(ResponseWriter, *Request))

Run on its own goroutine.

func (*http2serverConn) scheduleFrameWrite

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 (*http2serverConn) sendServeMsg

func (sc *http2serverConn) sendServeMsg(msg interface{})

func (*http2serverConn) sendWindowUpdate

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

st may be nil for conn-level

func (*http2serverConn) sendWindowUpdate32

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

st may be nil for conn-level

func (*http2serverConn) serve

func (sc *http2serverConn) serve()

func (*http2serverConn) setConnState

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 (*http2serverConn) shutDownIn

func (sc *http2serverConn) shutDownIn(d time.Duration)

func (*http2serverConn) startFrameWrite

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 (*http2serverConn) startGracefulShutdown

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 (*http2serverConn) startGracefulShutdownInternal

func (sc *http2serverConn) startGracefulShutdownInternal()

func (*http2serverConn) startPush

func (sc *http2serverConn) startPush(msg *http2startPushRequest)

func (*http2serverConn) state

func (sc *http2serverConn) state(streamID uint32) (http2streamState, *http2stream)

func (*http2serverConn) stopShutdownTimer

func (sc *http2serverConn) stopShutdownTimer()

func (*http2serverConn) vlogf

func (sc *http2serverConn) vlogf(format string, args ...interface{})

func (*http2serverConn) write100ContinueHeaders

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

called from handler goroutines.

func (*http2serverConn) writeDataFromHandler

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

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

func (*http2serverConn) writeFrame

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 (*http2serverConn) writeFrameAsync

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 (*http2serverConn) writeFrameFromHandler

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 (*http2serverConn) writeHeaders

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

called from handler goroutines. h may be nil.

func (*http2serverConn) wroteFrame

func (sc *http2serverConn) wroteFrame(res http2frameWriteResult)

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

type http2serverInternalState

type http2serverInternalState struct {
    mu          sync.Mutex
    activeConns map[*http2serverConn]struct{}
}

func (*http2serverInternalState) registerConn

func (s *http2serverInternalState) registerConn(sc *http2serverConn)

func (*http2serverInternalState) startGracefulShutdown

func (s *http2serverInternalState) startGracefulShutdown()

func (*http2serverInternalState) unregisterConn

func (s *http2serverInternalState) unregisterConn(sc *http2serverConn)

type http2serverMessage

type http2serverMessage int

type http2sortPriorityNodeSiblings

type http2sortPriorityNodeSiblings []*http2priorityNode

func (http2sortPriorityNodeSiblings) Len

func (z http2sortPriorityNodeSiblings) Len() int

func (http2sortPriorityNodeSiblings) Less

func (z http2sortPriorityNodeSiblings) Less(i, k int) bool

func (http2sortPriorityNodeSiblings) Swap

func (z http2sortPriorityNodeSiblings) Swap(i, k int)

type http2sorter

type http2sorter struct {
    v []string // owned by sorter
}

func (*http2sorter) Keys

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 (*http2sorter) Len

func (s *http2sorter) Len() int

func (*http2sorter) Less

func (s *http2sorter) Less(i, j int) bool

func (*http2sorter) SortStrings

func (s *http2sorter) SortStrings(ss []string)

func (*http2sorter) Swap

func (s *http2sorter) Swap(i, j int)

type http2startPushRequest

type http2startPushRequest struct {
    parent *http2stream
    method string
    url    *url.URL
    header Header
    done   chan error
}

type http2stickyErrWriter

type http2stickyErrWriter struct {
    w   io.Writer
    err *error
}

func (http2stickyErrWriter) Write

func (sew http2stickyErrWriter) Write(p []byte) (n int, err error)

type http2stream

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.

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
    parent           *http2stream // or nil
    numTrailerValues int64
    weight           uint8
    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
}

func (*http2stream) copyTrailersToHandlerRequest

func (st *http2stream) copyTrailersToHandlerRequest()

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

func (*http2stream) endStream

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 (*http2stream) isPushed

func (st *http2stream) isPushed() bool

isPushed reports whether the stream is server-initiated.

func (*http2stream) onWriteTimeout

func (st *http2stream) onWriteTimeout()

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

func (*http2stream) processTrailerHeaders

func (st *http2stream) processTrailerHeaders(f *http2MetaHeadersFrame) error

type http2streamEnder

type http2streamEnder interface {
    StreamEnded() bool
}

type http2streamState

type http2streamState int

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 (
    http2stateIdle http2streamState = iota
    http2stateOpen
    http2stateHalfClosedLocal
    http2stateHalfClosedRemote
    http2stateClosed
)

func (http2streamState) String

func (st http2streamState) String() string

type http2stringWriter

from pkg io

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

type http2transportResponseBody

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.

type http2transportResponseBody struct {
    cs *http2clientStream
}

func (http2transportResponseBody) Close

func (b http2transportResponseBody) Close() error

func (http2transportResponseBody) Read

func (b http2transportResponseBody) Read(p []byte) (n int, err error)

type http2write100ContinueHeadersFrame

type http2write100ContinueHeadersFrame struct {
    streamID uint32
}

func (http2write100ContinueHeadersFrame) staysWithinBuffer

func (w http2write100ContinueHeadersFrame) staysWithinBuffer(max int) bool

func (http2write100ContinueHeadersFrame) writeFrame

func (w http2write100ContinueHeadersFrame) writeFrame(ctx http2writeContext) error

type http2writeContext

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 http2writeContext interface {
    Framer() *http2Framer
    Flush() error
    CloseConn() error
    // HeaderEncoder returns an HPACK encoder that writes to the
    // returned buffer.
    HeaderEncoder() (*hpack.Encoder, *bytes.Buffer)
}

type http2writeData

type http2writeData struct {
    streamID  uint32
    p         []byte
    endStream bool
}

func (*http2writeData) String

func (w *http2writeData) String() string

func (*http2writeData) staysWithinBuffer

func (w *http2writeData) staysWithinBuffer(max int) bool

func (*http2writeData) writeFrame

func (w *http2writeData) writeFrame(ctx http2writeContext) error

type http2writeFramer

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

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
}

type http2writeGoAway

type http2writeGoAway struct {
    maxStreamID uint32
    code        http2ErrCode
}

func (*http2writeGoAway) staysWithinBuffer

func (*http2writeGoAway) staysWithinBuffer(max int) bool

func (*http2writeGoAway) writeFrame

func (p *http2writeGoAway) writeFrame(ctx http2writeContext) error

type http2writePingAck

type http2writePingAck struct{ pf *http2PingFrame }

func (http2writePingAck) staysWithinBuffer

func (w http2writePingAck) staysWithinBuffer(max int) bool

func (http2writePingAck) writeFrame

func (w http2writePingAck) writeFrame(ctx http2writeContext) error

type http2writePushPromise

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

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
}

func (*http2writePushPromise) staysWithinBuffer

func (w *http2writePushPromise) staysWithinBuffer(max int) bool

func (*http2writePushPromise) writeFrame

func (w *http2writePushPromise) writeFrame(ctx http2writeContext) error

func (*http2writePushPromise) writeHeaderBlock

func (w *http2writePushPromise) writeHeaderBlock(ctx http2writeContext, frag []byte, firstFrag, lastFrag bool) error

type http2writeQueue

writeQueue is used by implementations of WriteScheduler.

type http2writeQueue struct {
    s []http2FrameWriteRequest
}

func (*http2writeQueue) consume

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.

func (*http2writeQueue) empty

func (q *http2writeQueue) empty() bool

func (*http2writeQueue) push

func (q *http2writeQueue) push(wr http2FrameWriteRequest)

func (*http2writeQueue) shift

func (q *http2writeQueue) shift() http2FrameWriteRequest

type http2writeQueuePool

type http2writeQueuePool []*http2writeQueue

func (*http2writeQueuePool) get

func (p *http2writeQueuePool) get() *http2writeQueue

get returns an empty writeQueue.

func (*http2writeQueuePool) put

func (p *http2writeQueuePool) put(q *http2writeQueue)

put inserts an unused writeQueue into the pool.

type http2writeResHeaders

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

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
}

func (*http2writeResHeaders) staysWithinBuffer

func (w *http2writeResHeaders) staysWithinBuffer(max int) bool

func (*http2writeResHeaders) writeFrame

func (w *http2writeResHeaders) writeFrame(ctx http2writeContext) error

func (*http2writeResHeaders) writeHeaderBlock

func (w *http2writeResHeaders) writeHeaderBlock(ctx http2writeContext, frag []byte, firstFrag, lastFrag bool) error

type http2writeSettings

type http2writeSettings []http2Setting

func (http2writeSettings) staysWithinBuffer

func (s http2writeSettings) staysWithinBuffer(max int) bool

func (http2writeSettings) writeFrame

func (s http2writeSettings) writeFrame(ctx http2writeContext) error

type http2writeSettingsAck

type http2writeSettingsAck struct{}

func (http2writeSettingsAck) staysWithinBuffer

func (http2writeSettingsAck) staysWithinBuffer(max int) bool

func (http2writeSettingsAck) writeFrame

func (http2writeSettingsAck) writeFrame(ctx http2writeContext) error

type http2writeWindowUpdate

type http2writeWindowUpdate struct {
    streamID uint32 // or 0 for conn-level
    n        uint32
}

func (http2writeWindowUpdate) staysWithinBuffer

func (wu http2writeWindowUpdate) staysWithinBuffer(max int) bool

func (http2writeWindowUpdate) writeFrame

func (wu http2writeWindowUpdate) writeFrame(ctx http2writeContext) error

type httpError

type httpError struct {
    err     string
    timeout bool
}

func (*httpError) Error

func (e *httpError) Error() string

func (*httpError) Temporary

func (e *httpError) Temporary() bool

func (*httpError) Timeout

func (e *httpError) Timeout() bool

type httpRange

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

type httpRange struct {
    start, length int64
}

func (httpRange) contentRange

func (r httpRange) contentRange(size int64) string

func (httpRange) mimeHeader

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

type initALPNRequest

initALPNRequest is an HTTP handler that initializes certain uninitialized fields in its *Request. Such partially-initialized Requests come from ALPN protocol handlers.

type initALPNRequest struct {
    ctx context.Context
    c   *tls.Conn
    h   serverHandler
}

func (initALPNRequest) BaseContext

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 (initALPNRequest) ServeHTTP

func (h initALPNRequest) ServeHTTP(rw ResponseWriter, req *Request)

type keyValues

type keyValues struct {
    key    string
    values []string
}

type loggingConn

loggingConn is used for debugging.

type loggingConn struct {
    name string
    net.Conn
}

func (*loggingConn) Close

func (c *loggingConn) Close() (err error)

func (*loggingConn) Read

func (c *loggingConn) Read(p []byte) (n int, err error)

func (*loggingConn) Write

func (c *loggingConn) Write(p []byte) (n int, err error)

type maskedSig

type maskedSig struct {
    mask, pat []byte
    skipWS    bool
    ct        string
}

func (*maskedSig) match

func (m *maskedSig) match(data []byte, firstNonWS int) string

type maxBytesReader

type maxBytesReader struct {
    w   ResponseWriter
    r   io.ReadCloser // underlying reader
    n   int64         // max bytes remaining
    err error         // sticky error
}

func (*maxBytesReader) Close

func (l *maxBytesReader) Close() error

func (*maxBytesReader) Read

func (l *maxBytesReader) Read(p []byte) (n int, err error)

type mp4Sig

type mp4Sig struct{}

func (mp4Sig) match

func (mp4Sig) match(data []byte, firstNonWS int) string

type muxEntry

type muxEntry struct {
    h       Handler
    pattern string
}

func appendSorted

func appendSorted(es []muxEntry, e muxEntry) []muxEntry

type noBody

type noBody struct{}

func (noBody) Close

func (noBody) Close() error

func (noBody) Read

func (noBody) Read([]byte) (int, error)

func (noBody) WriteTo

func (noBody) WriteTo(io.Writer) (int64, error)

type nothingWrittenError

nothingWrittenError wraps a write errors which ended up writing zero bytes.

type nothingWrittenError struct {
    error
}

type onceCloseListener

onceCloseListener wraps a net.Listener, protecting it from multiple Close calls.

type onceCloseListener struct {
    net.Listener
    once     sync.Once
    closeErr error
}

func (*onceCloseListener) Close

func (oc *onceCloseListener) Close() error

func (*onceCloseListener) close

func (oc *onceCloseListener) close()

type persistConn

persistConn wraps a connection, usually a persistent one (but may be used for non-keep-alive requests as well)

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

func (*persistConn) Read

func (pc *persistConn) Read(p []byte) (n int, err error)

func (*persistConn) addTLS

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 (*persistConn) cancelRequest

func (pc *persistConn) cancelRequest(err error)

func (*persistConn) canceled

func (pc *persistConn) canceled() error

canceled returns non-nil if the connection was closed due to CancelRequest or due to context cancellation.

func (*persistConn) close

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 (*persistConn) closeConnIfStillIdle

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 (*persistConn) closeLocked

func (pc *persistConn) closeLocked(err error)

func (*persistConn) gotIdleConnTrace

func (pc *persistConn) gotIdleConnTrace(idleAt time.Time) (t httptrace.GotConnInfo)

func (*persistConn) isBroken

func (pc *persistConn) isBroken() bool

isBroken reports whether this connection is in a known broken state.

func (*persistConn) isReused

func (pc *persistConn) isReused() bool

isReused reports whether this connection has been used before.

func (*persistConn) mapRoundTripError

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 (*persistConn) markReused

func (pc *persistConn) markReused()

markReused marks this connection as having been successfully used for a request and response.

func (*persistConn) maxHeaderResponseSize

func (pc *persistConn) maxHeaderResponseSize() int64

func (*persistConn) readLoop

func (pc *persistConn) readLoop()

func (*persistConn) readLoopPeekFailLocked

func (pc *persistConn) readLoopPeekFailLocked(peekErr error)

func (*persistConn) readResponse

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 (*persistConn) roundTrip

func (pc *persistConn) roundTrip(req *transportRequest) (resp *Response, err error)

func (*persistConn) shouldRetryRequest

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 (*persistConn) waitForContinue

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 (*persistConn) writeLoop

func (pc *persistConn) writeLoop()

func (*persistConn) wroteRequest

func (pc *persistConn) wroteRequest() bool

wroteRequest is a check before recycling a connection that the previous write (from writeLoop above) happened and was successful.

type persistConnWriter

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.

type persistConnWriter struct {
    pc *persistConn
}

func (persistConnWriter) ReadFrom

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.

func (persistConnWriter) Write

func (w persistConnWriter) Write(p []byte) (n int, err error)

type populateResponse

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.

type populateResponse struct {
    res          *Response
    ch           chan *Response
    wroteHeader  bool
    hasContent   bool
    sentResponse bool
    pw           *io.PipeWriter
}

func newPopulateResponseWriter

func newPopulateResponseWriter() (*populateResponse, <-chan *Response)

func (*populateResponse) Header

func (pr *populateResponse) Header() Header

func (*populateResponse) Write

func (pr *populateResponse) Write(p []byte) (n int, err error)

func (*populateResponse) WriteHeader

func (pr *populateResponse) WriteHeader(code int)

func (*populateResponse) finish

func (pr *populateResponse) finish()

func (*populateResponse) sendResponse

func (pr *populateResponse) sendResponse()

type readResult

type readResult struct {
    n   int
    err error
    b   byte // byte read, if n == 1
}

type readWriteCloserBody

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.

type readWriteCloserBody struct {
    br *bufio.Reader // used until empty
    io.ReadWriteCloser
}

func (*readWriteCloserBody) Read

func (b *readWriteCloserBody) Read(p []byte) (n int, err error)

type redirectHandler

Redirect to a fixed URL

type redirectHandler struct {
    url  string
    code int
}

func (*redirectHandler) ServeHTTP

func (rh *redirectHandler) ServeHTTP(w ResponseWriter, r *Request)

type requestAndChan

type requestAndChan struct {
    req *Request
    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 requestBodyReadError

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 requestBodyReadError struct{ error }

type response

A response represents the server side of an HTTP response.

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"

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

func (*response) CloseNotify

func (w *response) CloseNotify() <-chan bool

func (*response) Flush

func (w *response) Flush()

func (*response) Header

func (w *response) Header() Header

func (*response) Hijack

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 (*response) ReadFrom

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.

func (*response) Write

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.

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

6. the rwc, the net.Conn.

TODO(bradfitz): short-circuit some of the buffering when the initial header contains both a Content-Type and Content-Length. Also short-circuit in (1) when the header's been sent and not in chunking mode, writing directly to (4) instead, if (2) has no buffered data. More generally, we could short-circuit from (1) to (3) even in chunking mode if the write size from (1) is over some threshold and nothing is in (2). The answer might be mostly making bufferBeforeChunkingSize smaller and having bufio's fast-paths deal with this instead.

func (*response) WriteHeader

func (w *response) WriteHeader(code int)

func (*response) WriteString

func (w *response) WriteString(data string) (n int, err error)

func (*response) bodyAllowed

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 (*response) closedRequestBodyEarly

func (w *response) closedRequestBodyEarly() bool

func (*response) declareTrailer

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 (*response) finalTrailers

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 (*response) finishRequest

func (w *response) finishRequest()

func (*response) needsSniff

func (w *response) needsSniff() bool

needsSniff reports whether a Content-Type still needs to be sniffed.

func (*response) requestTooLarge

func (w *response) requestTooLarge()

requestTooLarge is called by maxBytesReader when too much input has been read from the client.

func (*response) sendExpectationFailed

func (w *response) sendExpectationFailed()

func (*response) shouldReuseConnection

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 (*response) write

func (w *response) write(lenData int, dataB []byte, dataS string) (n int, err error)

either dataB or dataS is non-zero.

type responseAndError

responseAndError is how the goroutine reading from an HTTP/1 server communicates with the goroutine doing the RoundTrip.

type responseAndError struct {
    res *Response // else use this response (see res method)
    err error
}

type serverHandler

serverHandler delegates to either the server's Handler or DefaultServeMux and also handles "OPTIONS *" requests.

type serverHandler struct {
    srv *Server
}

func (serverHandler) ServeHTTP

func (sh serverHandler) ServeHTTP(rw ResponseWriter, req *Request)

type sniffSig

type sniffSig interface {
    // match returns the MIME type of the data, or "" if unknown.
    match(data []byte, firstNonWS int) string
}

type socksAddr

An Addr represents a SOCKS-specific address. Either Name or IP is used exclusively.

type socksAddr struct {
    Name string // fully-qualified domain name
    IP   net.IP
    Port int
}

func (*socksAddr) Network

func (a *socksAddr) Network() string

func (*socksAddr) String

func (a *socksAddr) String() string

type socksAuthMethod

An AuthMethod represents a SOCKS authentication method.

type socksAuthMethod int

type socksCommand

A Command represents a SOCKS command.

type socksCommand int

func (socksCommand) String

func (cmd socksCommand) String() string

type socksConn

A Conn represents a forward proxy connection.

type socksConn struct {
    net.Conn

    boundAddr net.Addr
}

func (*socksConn) BoundAddr

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

A Dialer holds SOCKS-specific options.

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
}

func socksNewDialer

func socksNewDialer(network, address string) *socksDialer

NewDialer returns a new Dialer that dials through the provided proxy server's network and address.

func (*socksDialer) Dial

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 (*socksDialer) DialContext

func (d *socksDialer) DialContext(ctx