Package-Level Type Names (total 111, in which 36 are exported)
/* sort exporteds by: | */
ClientConn is the state of a single HTTP/2 client connection to an
HTTP/2 server.
br*bufio.Readerbw*bufio.Writerclosedboolclosingbool
// hold mu; broadcast on flow/closed changes
// our conn-level flow control quota (cs.flow is per stream)
fr*FramerfreeBuf[][]byte
// if non-nil, the GoAwayFrame we received
// goAway frame's debug data, retained as a string
// HPACK encoder writes into this
henc*hpack.Encoder
// or 0 for never
idleTimer*time.Timer
// peer's conn-level flow control
initialWindowSizeuint32lastActivetime.Time
// time last idle
maxConcurrentStreamsuint32
Settings from peer: (also guarded by mu)
// guards following
nextStreamIDuint32peerMaxHeaderListSizeuint64
// requests blocked and waiting to be sent because len(streams) == maxConcurrentStreams
// in flight ping data to notification channel
readLoop goroutine fields:
// closed on error
// set before readerDone is closed
// whether conn is being reused; atomic
// whether being used for a single http.Request
// client-initiated
t*Transport
// usually *tls.Conn, except specialized impls
// nil only for specialized impls
// we sent a SETTINGS frame and haven't heard back
// first write error that has occurred
// held while writing; acquire AFTER mu if holding both
CanTakeNewRequest reports whether the connection can take a new request,
meaning it has not been closed or received or sent a GOAWAY.
Close closes the client connection immediately.
In-flight requests are interrupted. For a graceful shutdown, use Shutdown instead.
Ping sends a PING frame to the server and waits for the ack.
(*T) RoundTrip(req *http.Request) (*http.Response, error)
Shutdown gracefully close the client connection, waiting for running streams to complete.
awaitOpenSlotForRequest waits until len(streams) < maxConcurrentStreams.
Must hold cc.mu.
(*T) canTakeNewRequestLocked() bool
closes the client connection immediately. In-flight requests are interrupted.
err is sent to streams.
closes the client connection immediately. In-flight requests are interrupted.
(*T) closeIfIdle()
requires cc.mu be held.
requires cc.mu be held.
(*T) forgetStreamID(id uint32)
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.
(*T) healthCheck()(*T) idleState() clientConnIdleState(*T) idleStateLocked() (st clientConnIdleState)(*T) logf(format string, args ...interface{})
requires cc.mu be held.
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.
(*T) putFrameScratchBuffer(buf []byte)
readLoop runs in its own goroutine and reads and dispatches frames.
(*T) responseHeaderTimeout() time.Duration(*T) roundTrip(req *http.Request) (res *http.Response, gotErrAfterReqBodyWrite bool, err error)(*T) sendGoAway() error(*T) setGoAway(f *GoAwayFrame)(*T) streamByID(id uint32, andRemove bool) *clientStream
tooIdleLocked reports whether this connection has been been sitting idle
for too much wall time.
(*T) vlogf(format string, args ...interface{})(*T) writeHeader(name, value string)
requires cc.wmu be held
(*T) writeStreamReset(streamID uint32, code ErrCode, err error)
*T : database/sql/driver.Pinger
*T : io.Closer
*T : net/http.RoundTripper
func ClientConnPool.GetClientConn(req *http.Request, addr string) (*ClientConn, error)
func (*Transport).NewClientConn(c net.Conn) (*ClientConn, error)
func filterOutClientConn(in []*ClientConn, exclude *ClientConn) []*ClientConn
func (*Transport).dialClientConn(addr string, singleUse bool) (*ClientConn, error)
func (*Transport).newClientConn(c net.Conn, singleUse bool) (*ClientConn, error)
func ClientConnPool.MarkDead(*ClientConn)
func filterOutClientConn(in []*ClientConn, exclude *ClientConn) []*ClientConn
func filterOutClientConn(in []*ClientConn, exclude *ClientConn) []*ClientConn
func traceGotConn(req *http.Request, cc *ClientConn, reused bool)
ConnectionError is an error that results in the termination of the
entire connection.
( T) Error() string
T : error
A ContinuationFrame is used to continue a sequence of header block fragments.
See http://http2.github.io/http2-spec/#rfc.section.6.10
FrameHeaderFrameHeader
Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type.
Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement.
StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0.
Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame).
// caller can access []byte fields in the Frame
headerFragBuf[]byte
Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.
(*T) HeaderBlockFragment() []byte(*T) HeadersEnded() bool( T) String() string(*T) checkValid()(*T) invalidate()( T) writeDebug(buf *bytes.Buffer)
*T : Frame
T : expvar.Var
T : fmt.Stringer
*T : headersEnder
*T : headersOrContinuation
T : context.stringer
*T : net/http.http2headersEnder
*T : net/http.http2headersOrContinuation
T : runtime.stringer
A DataFrame conveys arbitrary, variable-length sequences of octets
associated with a stream.
See http://http2.github.io/http2-spec/#rfc.section.6.1
FrameHeaderFrameHeader
Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type.
Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement.
StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0.
Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame).
data[]byte
// caller can access []byte fields in the Frame
Data returns the frame's data octets, not including any padding
size byte or padding suffix bytes.
The caller must not retain the returned memory past the next
call to ReadFrame.
Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.
(*T) StreamEnded() bool( T) String() string(*T) checkValid()(*T) invalidate()( T) writeDebug(buf *bytes.Buffer)
*T : Frame
T : expvar.Var
T : fmt.Stringer
*T : streamEnder
T : context.stringer
*T : net/http.http2streamEnder
T : runtime.stringer
A Framer reads and writes Frames.
AllowIllegalReads permits the Framer's ReadFrame method
to return non-compliant frames or frame orders.
This is for testing and permits using the Framer to test
other HTTP/2 implementations' conformance to the spec.
It is not compatible with ReadMetaHeaders.
AllowIllegalWrites permits the Framer's Write methods to
write frames that do not conform to the HTTP/2 spec. This
permits using the Framer to test other HTTP/2
implementations' conformance to the spec.
If false, the Write methods will prefer to return an error
rather than comply.
MaxHeaderListSize is the http2 MAX_HEADER_LIST_SIZE.
It's used only if ReadMetaHeaders is set; 0 means a sane default
(currently 16MB)
If the limit is hit, MetaHeadersFrame.Truncated is set true.
ReadMetaHeaders if non-nil causes ReadFrame to merge
HEADERS and CONTINUATION frames together and return
MetaHeadersFrame instead.
// only use for logging written writes
debugFramerBuf*bytes.BufferdebugReadLoggerffunc(string, ...interface{})debugWriteLoggerffunc(string, ...interface{})errDetailerror
// nil if frames aren't reused (default)
TODO: let getReadBuf be configurable, and use a less memory-pinning
allocator in server.go to minimize memory pinned for many idle conns.
Will probably also need to make frame invalidation have a hook too.
headerBuf[9]bytelastFrameFrame
lastHeaderStream is non-zero if the last frame was an
unfinished HEADERS/CONTINUATION.
logReadsboollogWritesboolmaxReadSizeuint32
// zero means unlimited; TODO: implement
rio.Reader
// cache for default getReadBuf
wio.Writerwbuf[]byte
ErrorDetail returns a more detailed error of the last error
returned by Framer.ReadFrame. For instance, if ReadFrame
returns a StreamError with code PROTOCOL_ERROR, ErrorDetail
will say exactly what was invalid. ErrorDetail is not guaranteed
to return a non-nil value and like the rest of the http2 package,
its return value is not protected by an API compatibility promise.
ErrorDetail is reset after the next call to ReadFrame.
ReadFrame reads a single frame. The returned Frame is only valid
until the next call to ReadFrame.
If the frame is larger than previously set with SetMaxReadFrameSize, the
returned error is ErrFrameTooLarge. Other errors may be of type
ConnectionError, StreamError, or anything else from the underlying
reader.
SetMaxReadFrameSize sets the maximum size of a frame
that will be read by a subsequent call to ReadFrame.
It is the caller's responsibility to advertise this
limit with a SETTINGS frame.
SetReuseFrames allows the Framer to reuse Frames.
If called on a Framer, Frames returned by calls to ReadFrame are only
valid until the next call to ReadFrame.
WriteContinuation writes a CONTINUATION frame.
It will perform exactly one Write to the underlying Writer.
It is the caller's responsibility to not call other Write methods concurrently.
WriteData writes a DATA frame.
It will perform exactly one Write to the underlying Writer.
It is the caller's responsibility not to violate the maximum frame size
and to not call other Write methods concurrently.
WriteDataPadded writes a DATA frame with optional padding.
If pad is nil, the padding bit is not sent.
The length of pad must not exceed 255 bytes.
The bytes of pad must all be zero, unless f.AllowIllegalWrites is set.
It will perform exactly one Write to the underlying Writer.
It is the caller's responsibility not to violate the maximum frame size
and to not call other Write methods concurrently.
(*T) WriteGoAway(maxStreamID uint32, code ErrCode, debugData []byte) error
WriteHeaders writes a single HEADERS frame.
This is a low-level header writing method. Encoding headers and
splitting them into any necessary CONTINUATION frames is handled
elsewhere.
It will perform exactly one Write to the underlying Writer.
It is the caller's responsibility to not call other Write methods concurrently.
(*T) WritePing(ack bool, data [8]byte) error
WritePriority writes a PRIORITY frame.
It will perform exactly one Write to the underlying Writer.
It is the caller's responsibility to not call other Write methods concurrently.
WritePushPromise writes a single PushPromise Frame.
As with Header Frames, This is the low level call for writing
individual frames. Continuation frames are handled elsewhere.
It will perform exactly one Write to the underlying Writer.
It is the caller's responsibility to not call other Write methods concurrently.
WriteRSTStream writes a RST_STREAM frame.
It will perform exactly one Write to the underlying Writer.
It is the caller's responsibility to not call other Write methods concurrently.
WriteRawFrame writes a raw frame. This can be used to write
extension frames unknown to this package.
WriteSettings writes a SETTINGS frame with zero or more settings
specified and the ACK bit not set.
It will perform exactly one Write to the underlying Writer.
It is the caller's responsibility to not call other Write methods concurrently.
WriteSettingsAck writes an empty SETTINGS frame with the ACK bit set.
It will perform exactly one Write to the underlying Writer.
It is the caller's responsibility to not call other Write methods concurrently.
WriteWindowUpdate writes a WINDOW_UPDATE frame.
The increment value must be between 1 and 2,147,483,647, inclusive.
If the Stream ID is zero, the window update applies to the
connection as a whole.
checkFrameOrder reports an error if f is an invalid frame to return
next from ReadFrame. Mostly it checks whether HEADERS and
CONTINUATION frames are contiguous.
connError returns ConnectionError(code) but first
stashes away a public reason to the caller can optionally relay it
to the peer before hanging up on them. This might help others debug
their implementations.
(*T) endWrite() error(*T) logWrite()(*T) maxHeaderListSize() uint32(*T) maxHeaderStringLen() int
readMetaFrame returns 0 or more CONTINUATION frames from fr and
merge them into the provided hf and returns a MetaHeadersFrame
with the decoded hpack values.
(*T) startWrite(ftype FrameType, flags Flags, streamID uint32)(*T) writeByte(v byte)(*T) writeBytes(v []byte)(*T) writeUint16(v uint16)(*T) writeUint32(v uint32)
func NewFramer(w io.Writer, r io.Reader) *Framer
FrameWriteRequest is a request to write a frame.
done, if non-nil, must be a buffered channel with space for
1 message and is sent the return value from write (or an
earlier error) when the frame has been written.
stream is the stream on which this frame will be written.
nil for non-stream frames like PING and SETTINGS.
write is the interface value that does the writing, once the
WriteScheduler has selected this frame to write. The write
functions are all defined in write.go.
Consume consumes min(n, available) bytes from this frame, where available
is the number of flow control bytes available on the stream. Consume returns
0, 1, or 2 frames, where the integer return value gives the number of frames
returned.
If flow control prevents consuming any bytes, this returns (_, _, 0). If
the entire frame was consumed, this returns (wr, _, 1). Otherwise, this
returns (consumed, rest, 2), where 'consumed' contains the consumed bytes and
'rest' contains the remaining bytes. The consumed bytes are deducted from the
underlying stream's flow control budget.
DataSize returns the number of flow control bytes that must be consumed
to write this entire frame. This is 0 for non-DATA frames.
StreamID returns the id of the stream this frame will be written to.
0 is used for non-stream frames such as PING and SETTINGS.
String is for debugging only.
isControl reports whether wr is a control frame for MaxQueuedControlFrames
purposes. That includes non-stream frames and RST_STREAM frames.
replyToWriter sends err to wr.done and panics if the send must block
This does nothing if wr.done is nil.
T : expvar.Var
T : fmt.Stringer
T : context.stringer
T : runtime.stringer
func FrameWriteRequest.Consume(n int32) (FrameWriteRequest, FrameWriteRequest, int)
func FrameWriteRequest.Consume(n int32) (FrameWriteRequest, FrameWriteRequest, int)
func WriteScheduler.Pop() (wr FrameWriteRequest, ok bool)
func WriteScheduler.Push(wr FrameWriteRequest)
A GoAwayFrame informs the remote peer to stop creating streams on this connection.
See http://http2.github.io/http2-spec/#rfc.section.6.8
ErrCodeErrCodeFrameHeaderFrameHeader
Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type.
Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement.
StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0.
Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame).
LastStreamIDuint32debugData[]byte
// caller can access []byte fields in the Frame
DebugData returns any debug data in the GOAWAY frame. Its contents
are not defined.
The caller must not retain the returned memory past the next
call to ReadFrame.
Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.
( T) String() string(*T) checkValid()(*T) invalidate()( T) writeDebug(buf *bytes.Buffer)
*T : Frame
T : expvar.Var
T : fmt.Stringer
T : context.stringer
T : runtime.stringer
func (*ClientConn).setGoAway(f *GoAwayFrame)
A HeadersFrame is used to open a stream and additionally carries a
header block fragment.
FrameHeaderFrameHeader
Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type.
Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement.
StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0.
Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame).
Priority is set if FlagHeadersPriority is set in the FrameHeader.
// caller can access []byte fields in the Frame
// not owned
(*T) HasPriority() bool
Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.
(*T) HeaderBlockFragment() []byte(*T) HeadersEnded() bool(*T) StreamEnded() bool( T) String() string(*T) checkValid()(*T) invalidate()( T) writeDebug(buf *bytes.Buffer)
*T : Frame
T : expvar.Var
T : fmt.Stringer
*T : headersEnder
*T : headersOrContinuation
*T : streamEnder
T : context.stringer
*T : net/http.http2headersEnder
*T : net/http.http2headersOrContinuation
*T : net/http.http2streamEnder
T : runtime.stringer
func (*Framer).readMetaFrame(hf *HeadersFrame) (*MetaHeadersFrame, error)
HeadersFrameParam are the parameters for writing a HEADERS frame.
BlockFragment is part (or all) of a Header Block.
EndHeaders indicates that this frame contains an entire
header block and is not followed by any
CONTINUATION frames.
EndStream indicates that the header block is the last that
the endpoint will send for the identified stream. Setting
this flag causes the stream to enter one of "half closed"
states.
PadLength is the optional number of bytes of zeros to add
to this frame.
Priority, if non-zero, includes stream priority information
in the HEADER frame.
StreamID is the required Stream ID to initiate.
func (*Framer).WriteHeaders(p HeadersFrameParam) error
A MetaHeadersFrame is the representation of one HEADERS frame and
zero or more contiguous CONTINUATION frames and the decoding of
their HPACK-encoded contents.
This type of frame does not appear on the wire and is only returned
by the Framer when Framer.ReadMetaHeaders is set.
Fields are the fields contained in the HEADERS and
CONTINUATION frames. The underlying slice is owned by the
Framer and must not be retained after the next call to
ReadFrame.
Fields are guaranteed to be in the correct http2 order and
not have unknown pseudo header fields or invalid header
field names or values. Required pseudo header fields may be
missing, however. Use the MetaHeadersFrame.Pseudo accessor
method access pseudo headers.
HeadersFrame*HeadersFrameHeadersFrame.FrameHeaderFrameHeader
Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type.
Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement.
StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0.
Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame).
Priority is set if FlagHeadersPriority is set in the FrameHeader.
Truncated is whether the max header list size limit was hit
and Fields is incomplete. The hpack decoder state is still
valid, however.
// caller can access []byte fields in the Frame
// not owned
( T) HasPriority() bool
Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.
( T) HeaderBlockFragment() []byte( T) HeadersEnded() bool
PseudoFields returns the pseudo header fields of mh.
The caller does not own the returned slice.
PseudoValue returns the given pseudo header field's value.
The provided pseudo field should not contain the leading colon.
RegularFields returns the regular (non-pseudo) header fields of mh.
The caller does not own the returned slice.
( T) StreamEnded() bool( T) String() string(*T) checkPseudos() error( T) checkValid()( T) invalidate()( T) writeDebug(buf *bytes.Buffer)
T : Frame
T : expvar.Var
T : fmt.Stringer
T : headersEnder
T : headersOrContinuation
T : streamEnder
T : context.stringer
T : net/http.http2headersEnder
T : net/http.http2headersOrContinuation
T : net/http.http2streamEnder
T : runtime.stringer
func (*Framer).readMetaFrame(hf *HeadersFrame) (*MetaHeadersFrame, error)
OpenStreamOptions specifies extra options for WriteScheduler.OpenStream.
PusherID is zero if the stream was initiated by the client. Otherwise,
PusherID names the stream that pushed the newly opened stream.
func WriteScheduler.OpenStream(streamID uint32, options OpenStreamOptions)
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
Data[8]byteFrameHeaderFrameHeader
Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type.
Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement.
StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0.
Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame).
// caller can access []byte fields in the Frame
Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.
(*T) IsAck() bool( T) String() string(*T) checkValid()(*T) invalidate()( T) writeDebug(buf *bytes.Buffer)
*T : Frame
T : expvar.Var
T : fmt.Stringer
T : context.stringer
T : runtime.stringer
A PriorityFrame specifies the sender-advised priority of a stream.
See http://http2.github.io/http2-spec/#rfc.section.6.3
FrameHeaderFrameHeader
Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type.
Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement.
StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0.
Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame).
PriorityParamPriorityParam
Exclusive is whether the dependency is exclusive.
StreamDep is a 31-bit stream identifier for the
stream that this stream depends on. Zero means no
dependency.
Weight is the stream's zero-indexed weight. It should be
set together with StreamDep, or neither should be set. Per
the spec, "Add one to the value to obtain a weight between
1 and 256."
// caller can access []byte fields in the Frame
Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.
( T) IsZero() bool( T) String() string(*T) checkValid()(*T) invalidate()( T) writeDebug(buf *bytes.Buffer)
*T : Frame
T : expvar.Var
T : fmt.Stringer
T : gopkg.in/yaml.v2.IsZeroer
T : context.stringer
T : runtime.stringer
PriorityParam are the stream prioritzation parameters.
Exclusive is whether the dependency is exclusive.
StreamDep is a 31-bit stream identifier for the
stream that this stream depends on. Zero means no
dependency.
Weight is the stream's zero-indexed weight. It should be
set together with StreamDep, or neither should be set. Per
the spec, "Add one to the value to obtain a weight between
1 and 256."
( T) IsZero() bool
T : gopkg.in/yaml.v2.IsZeroer
func (*Framer).WritePriority(streamID uint32, p PriorityParam) error
func WriteScheduler.AdjustStream(streamID uint32, priority PriorityParam)
func checkPriority(streamID uint32, p PriorityParam) error
PriorityWriteSchedulerConfig configures a priorityWriteScheduler.
MaxClosedNodesInTree controls the maximum number of closed streams to
retain in the priority tree. Setting this to zero saves a small amount
of memory at the cost of performance.
See RFC 7540, Section 5.3.4:
"It is possible for a stream to become closed while prioritization
information ... is in transit. ... This potentially creates suboptimal
prioritization, since the stream could be given a priority that is
different from what is intended. To avoid these problems, an endpoint
SHOULD retain stream prioritization state for a period after streams
become closed. The longer state is retained, the lower the chance that
streams are assigned incorrect or default priority values."
MaxIdleNodesInTree controls the maximum number of idle streams to
retain in the priority tree. Setting this to zero saves a small amount
of memory at the cost of performance.
See RFC 7540, Section 5.3.4:
Similarly, streams that are in the "idle" state can be assigned
priority or become a parent of other streams. This allows for the
creation of a grouping node in the dependency tree, which enables
more flexible expressions of priority. Idle streams begin with a
default priority (Section 5.3.5).
ThrottleOutOfOrderWrites enables write throttling to help ensure that
data is delivered in priority order. This works around a race where
stream B depends on stream A and both streams are about to call Write
to queue DATA frames. If B wins the race, a naive scheduler would eagerly
write as much data from B as possible, but this is suboptimal because A
is a higher-priority stream. With throttling enabled, we write a small
amount of data from B to minimize the amount of bandwidth that B can
steal from A.
func NewPriorityWriteScheduler(cfg *PriorityWriteSchedulerConfig) WriteScheduler
A PushPromiseFrame is used to initiate a server stream.
See http://http2.github.io/http2-spec/#rfc.section.6.6
FrameHeaderFrameHeader
Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type.
Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement.
StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0.
Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame).
PromiseIDuint32
// caller can access []byte fields in the Frame
// not owned
Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.
(*T) HeaderBlockFragment() []byte(*T) HeadersEnded() bool( T) String() string(*T) checkValid()(*T) invalidate()( T) writeDebug(buf *bytes.Buffer)
*T : Frame
T : expvar.Var
T : fmt.Stringer
*T : headersEnder
*T : headersOrContinuation
T : context.stringer
*T : net/http.http2headersEnder
*T : net/http.http2headersOrContinuation
T : runtime.stringer
PushPromiseParam are the parameters for writing a PUSH_PROMISE frame.
BlockFragment is part (or all) of a Header Block.
EndHeaders indicates that this frame contains an entire
header block and is not followed by any
CONTINUATION frames.
PadLength is the optional number of bytes of zeros to add
to this frame.
PromiseID is the required Stream ID which this
Push Promises
StreamID is the required Stream ID to initiate.
func (*Framer).WritePushPromise(p PushPromiseParam) error
RoundTripOpt are options for the Transport.RoundTripOpt method.
OnlyCachedConn controls whether RoundTripOpt may
create a new TCP connection. If set true and
no cached connection is available, RoundTripOpt
will return ErrNoCachedConn.
func (*Transport).RoundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Response, error)
A RSTStreamFrame allows for abnormal termination of a stream.
See http://http2.github.io/http2-spec/#rfc.section.6.4
ErrCodeErrCodeFrameHeaderFrameHeader
Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type.
Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement.
StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0.
Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame).
// caller can access []byte fields in the Frame
Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.
( T) String() string(*T) checkValid()(*T) invalidate()( T) writeDebug(buf *bytes.Buffer)
*T : Frame
T : expvar.Var
T : fmt.Stringer
T : context.stringer
T : runtime.stringer
ServeConnOpts are options for the Server.ServeConn method.
BaseConfig optionally sets the base configuration
for values. If nil, defaults are used.
Context is the base context to use.
If nil, context.Background is used.
Handler specifies which handler to use for processing
requests. If nil, BaseConfig.Handler is used. If BaseConfig
or BaseConfig.Handler is nil, http.DefaultServeMux is used.
(*T) baseConfig() *http.Server(*T) context() context.Context(*T) handler() http.Handler
func (*Server).ServeConn(c net.Conn, opts *ServeConnOpts)
func serverConnBaseContext(c net.Conn, opts *ServeConnOpts) (ctx context.Context, cancel func())
Server is an HTTP/2 server.
IdleTimeout specifies how long until idle clients should be
closed with a GOAWAY frame. PING frames are not considered
activity for the purposes of IdleTimeout.
MaxConcurrentStreams optionally specifies the number of
concurrent streams that each client may have open at a
time. This is unrelated to the number of http.Handler goroutines
which may be active globally, which is MaxHandlers.
If zero, MaxConcurrentStreams defaults to at least 100, per
the HTTP/2 spec's recommendations.
MaxHandlers limits the number of http.Handler ServeHTTP goroutines
which may run at a time over all connections.
Negative or zero no limit.
TODO: implement
MaxReadFrameSize optionally specifies the largest frame
this server is willing to read. A valid value is between
16k and 16M, inclusive. If zero or otherwise invalid, a
default value is used.
MaxUploadBufferPerConnection is the size of the initial flow
control window for each connections. The HTTP/2 spec does not
allow this to be smaller than 65535 or larger than 2^32-1.
If the value is outside this range, a default value will be
used instead.
MaxUploadBufferPerStream is the size of the initial flow control
window for each stream. The HTTP/2 spec does not allow this to
be larger than 2^32-1. If the value is zero or larger than the
maximum, a default value will be used instead.
NewWriteScheduler constructs a write scheduler for a connection.
If nil, a default scheduler is chosen.
PermitProhibitedCipherSuites, if true, permits the use of
cipher suites prohibited by the HTTP/2 spec.
Internal state. This is a pointer (rather than embedded directly)
so that we don't embed a Mutex in this struct, which will make the
struct non-copyable, which might break some callers.
ServeConn serves HTTP/2 requests on the provided connection and
blocks until the connection is no longer readable.
ServeConn starts speaking HTTP/2 assuming that c has not had any
reads or writes. It writes its initial settings frame and expects
to be able to read the preface and settings frame from the
client. If c has a ConnectionState method like a *tls.Conn, the
ConnectionState is used to verify the TLS ciphersuite and to set
the Request.TLS field in Handlers.
ServeConn does not support h2c by itself. Any h2c support must be
implemented in terms of providing a suitably-behaving net.Conn.
The opts parameter is optional. If nil, default values are used.
(*T) initialConnRecvWindowSize() int32(*T) initialStreamRecvWindowSize() int32(*T) maxConcurrentStreams() uint32
maxQueuedControlFrames is the maximum number of control frames like
SETTINGS, PING and RST_STREAM that will be queued for writing before
the connection is closed to prevent memory exhaustion attacks.
(*T) maxReadFrameSize() uint32
func ConfigureServer(s *http.Server, conf *Server) error
Setting is a setting parameter: which setting it is, and its value.
ID is which setting is being set.
See http://http2.github.io/http2-spec/#SettingValues
Val is the value.
( T) String() string
Valid reports whether the setting is valid.
T : expvar.Var
T : fmt.Stringer
T : context.stringer
T : runtime.stringer
func (*SettingsFrame).Setting(i int) Setting
func (*Framer).WriteSettings(settings ...Setting) error
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
FrameHeaderFrameHeader
Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type.
Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement.
StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0.
Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame).
// caller can access []byte fields in the Frame
p[]byte
ForeachSetting runs fn for each setting.
It stops and returns the first error.
HasDuplicates reports whether f contains any duplicate setting IDs.
Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.
(*T) IsAck() bool(*T) NumSettings() int
Setting returns the setting from the frame at the given 0-based index.
The index must be >= 0 and less than f.NumSettings().
( T) String() string(*T) Value(id SettingID) (v uint32, ok bool)(*T) checkValid()(*T) invalidate()( T) writeDebug(buf *bytes.Buffer)
*T : Frame
T : expvar.Var
T : fmt.Stringer
T : context.stringer
T : runtime.stringer
Transport is an HTTP/2 Transport.
A Transport internally caches connections to servers. It is safe
for concurrent use by multiple goroutines.
AllowHTTP, if true, permits HTTP/2 requests using the insecure,
plain-text "http" scheme. Note that this does not enable h2c support.
ConnPool optionally specifies an alternate connection pool to use.
If nil, the default is used.
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.
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.
MaxHeaderListSize is the http2 SETTINGS_MAX_HEADER_LIST_SIZE to
send in the initial settings frame. It is how many bytes
of response headers are allowed. Unlike the http2 spec, zero here
means to use a default limit (currently 10MB). If you actually
want to advertise an unlimited value to the peer, Transport
interprets the highest possible value here (0xffffffff or 1<<32-1)
to mean no limit.
PingTimeout is the timeout after which the connection will be closed
if a response to Ping is not received.
Defaults to 15s.
ReadIdleTimeout is the timeout after which a health check using ping
frame will be carried out if no frame is received on the connection.
Note that a ping response will is considered a received frame, so if
there is no other traffic on the connection, the health check will
be performed every ReadIdleTimeout interval.
If zero, no health check is performed.
StrictMaxConcurrentStreams controls whether the server's
SETTINGS_MAX_CONCURRENT_STREAMS should be respected
globally. If false, new TCP connections are created to the
server as needed to keep each under the per-connection
SETTINGS_MAX_CONCURRENT_STREAMS limit. If true, the
server's SETTINGS_MAX_CONCURRENT_STREAMS is interpreted as
a global limit and callers of RoundTrip block when needed,
waiting for their turn.
TLSClientConfig specifies the TLS configuration to use with
tls.Client. If nil, the default configuration is used.
connPoolOncesync.Once
// non-nil version of ConnPool
t1, if non-nil, is the standard library Transport using
this transport. Its settings are used (but not its
RoundTrip method, etc).
CloseIdleConnections closes any connections which were previously
connected from previous requests but are now sitting idle.
It does not interrupt any connections currently in use.
(*T) NewClientConn(c net.Conn) (*ClientConn, error)(*T) RoundTrip(req *http.Request) (*http.Response, error)
RoundTripOpt is like RoundTrip, but takes options.
(*T) connPool() ClientConnPool(*T) dialClientConn(addr string, singleUse bool) (*ClientConn, error)(*T) dialTLS() func(string, string, *tls.Config) (net.Conn, error)(*T) dialTLSDefault(network, addr string, cfg *tls.Config) (net.Conn, error)(*T) disableCompression() bool
disableKeepAlives reports whether connections should be closed as
soon as possible after handling the first request.
(*T) expectContinueTimeout() time.Duration(*T) getBodyWriterState(cs *clientStream, body io.Reader) (s bodyWriterState)(*T) idleConnTimeout() time.Duration(*T) initConnPool()(*T) logf(format string, args ...interface{})(*T) maxHeaderListSize() uint32(*T) newClientConn(c net.Conn, singleUse bool) (*ClientConn, error)(*T) newTLSConfig(host string) *tls.Config(*T) pingTimeout() time.Duration(*T) vlogf(format string, args ...interface{})
*T : net/http.RoundTripper
*T : net/http.h2Transport
*T : net/http/httptest.closeIdleTransport
func ConfigureTransports(t1 *http.Transport) (*Transport, error)
func configureTransports(t1 *http.Transport) (*Transport, error)
An UnknownFrame is the frame type returned when the frame type is unknown
or no specific frame type parser exists.
FrameHeaderFrameHeader
Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type.
Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement.
StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0.
Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame).
// caller can access []byte fields in the Frame
p[]byte
Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.
Payload returns the frame's payload (after the header). It is not
valid to call this method after a subsequent call to
Framer.ReadFrame, nor is it valid to retain the returned slice.
The memory is owned by the Framer and is invalidated when the next
frame is read.
( T) String() string(*T) checkValid()(*T) invalidate()( T) writeDebug(buf *bytes.Buffer)
*T : Frame
T : expvar.Var
T : fmt.Stringer
T : context.stringer
T : runtime.stringer
A WindowUpdateFrame is used to implement flow control.
See http://http2.github.io/http2-spec/#rfc.section.6.9
FrameHeaderFrameHeader
Flags are the 1 byte of 8 potential bit flags per frame.
They are specific to the frame type.
Length is the length of the frame, not including the 9 byte header.
The maximum size is one byte less than 16MB (uint24), but only
frames up to 16KB are allowed without peer agreement.
StreamID is which stream this frame is for. Certain frames
are not stream-specific, in which case this field is 0.
Type is the 1 byte frame type. There are ten standard frame
types, but extension frame types may be written by WriteRawFrame
and will be returned by ReadFrame (as UnknownFrame).
// never read with high bit set
// caller can access []byte fields in the Frame
Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.
( T) String() string(*T) checkValid()(*T) invalidate()( T) writeDebug(buf *bytes.Buffer)
*T : Frame
T : expvar.Var
T : fmt.Stringer
T : context.stringer
T : runtime.stringer
WriteScheduler is the interface implemented by HTTP/2 write schedulers.
Methods are never called concurrently.
AdjustStream adjusts the priority of the given stream. This may be called
on a stream that has not yet been opened or has been closed. Note that
RFC 7540 allows PRIORITY frames to be sent on streams in any state. See:
https://tools.ietf.org/html/rfc7540#section-5.1
CloseStream closes a stream in the write scheduler. Any frames queued on
this stream should be discarded. It is illegal to call this on a stream
that is not open -- the call may panic.
OpenStream opens a new stream in the write scheduler.
It is illegal to call this with streamID=0 or with a streamID that is
already open -- the call may panic.
Pop dequeues the next frame to write. Returns false if no frames can
be written. Frames with a given wr.StreamID() are Pop'd in the same
order they are Push'd. No frames should be discarded except by CloseStream.
Push queues a frame in the scheduler. In most cases, this will not be
called with wr.StreamID()!=0 unless that stream is currently open. The one
exception is RST_STREAM frames, which may be sent on idle or closed streams.
*priorityWriteScheduler
*randomWriteScheduler
func NewPriorityWriteScheduler(cfg *PriorityWriteSchedulerConfig) WriteScheduler
func NewRandomWriteScheduler() WriteScheduler
A bodyReadMsg tells the server loop that the http.Handler read n
bytes of the DATA from the client on the given stream.
nintst*stream
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".
cs*clientStream
// how long we should delay a delayed write for
// the code to run in the goroutine, writing the body
// to call fn with
// result of fn's execution
// if non-nil, we're doing a delayed write
( T) cancel()( T) on100()
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.
func (*Transport).getBodyWriterState(cs *clientStream, body io.Reader) (s bodyWriterState)
bufferedWriter is a buffered writer that writes to w.
Its buffered writer is lazily allocated as needed, to minimize
idle memory usage with many connections.
// non-nil when data is buffered
// immutable
(*T) Available() int(*T) Flush() error(*T) Write(p []byte) (n int, err error)
*T : github.com/go-git/go-git/v5/plumbing/protocol/packp/sideband.Progress
*T : github.com/jbenet/go-context/io.Writer
*T : io.Writer
func newBufferedWriter(w io.Writer) *bufferedWriter
clientConnIdleState describes the suitability of a client
connection to initiate a new RoundTrip request.
canTakeNewRequestbool
// whether it's unused by any previous request
func (*ClientConn).idleState() clientConnIdleState
func (*ClientConn).idleStateLocked() (st clientConnIdleState)
TODO: use singleflight for dialing and addConnCalls?
// in-flight addConnIfNeede calls
TODO: add support for sharing conns based on cert names
(e.g. share conn for googleapis.com and appspot.com)
// key is host:port
// currently in-flight dials
keysmap[*ClientConn][]string
// TODO: maybe switch to RWMutex
t*Transport(*T) GetClientConn(req *http.Request, addr string) (*ClientConn, error)(*T) MarkDead(cc *ClientConn)
addConnIfNeeded makes a NewClientConn out of c if a connection for key doesn't
already exist. It coalesces concurrent calls with the same key.
This is used by the http1 Transport code when it creates a new connection. Because
the http1 Transport doesn't de-dup TCP dials to outbound hosts (because it doesn't know
the protocol), it can get into a situation where it has multiple TLS connections.
This code decides which ones live or die.
The return value used is whether c was used.
c is never closed.
p.mu must be held
(*T) closeIdleConnections()(*T) getClientConn(req *http.Request, addr string, dialOnMiss bool) (*ClientConn, error)
requires p.mu is held.
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.
*T : ClientConnPool
*T : clientConnPoolIdleCloser
clientStream is the state for a single HTTP/2 stream. One of these
is created for each Transport.RoundTrip call.
IDuint32
// buffered pipe with the flow-controlled response payload
// -1 means unknown; owned by transportResponseBody.Read
cc*ClientConn
// whether we sent a RST_STREAM to the server; guarded by cc.mu
// closed when stream remove from cc.streams map; close calls guarded by cc.mu
owned by clientConnReadLoop:
// got the first response byte
// guarded by cc.mu
// guarded by cc.mu
// number of 1xx responses seen
// optional code to run if get a 100 continue response
// got first MetaHeadersFrame (actual headers)
// got optional second MetaHeadersFrame (trailers)
// closed on peer reset
// sticky read error; owned by transportResponseBody.Read
req*http.RequestrequestedGzipbool
// client's Response.Trailer
rescchan resAndError
// populated before peerReset is closed
// started request body write; guarded by cc.mu
// if non-nil, stop writing req body; guarded by cc.mu
// or nil
// accumulated trailers
(*T) abortRequestBodyWrite(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.
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.
(*T) cancelStream()
checkResetOrDone reports any error sent in a RST_STREAM frame by the
server, or errStreamClosed if the stream is complete.
(*T) copyTrailers()
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.
(*T) getStartedWrite() bool(*T) writeRequestBody(body io.Reader, bodyCloser io.Closer) (err error)
func (*ClientConn).newStream() *clientStream
func (*ClientConn).streamByID(id uint32, andRemove bool) *clientStream
func (*Transport).getBodyWriterState(cs *clientStream, body io.Reader) (s bodyWriterState)
A closeWaiter is like a sync.WaitGroup but only goes 1 to 0 (open to closed).
Close marks the closeWaiter as closed and unblocks any waiters.
Init makes a closeWaiter usable.
It exists because so a closeWaiter value can be placed inside a
larger struct and have the Mutex and Cond's memory in the same
allocation.
Wait waits for the closeWaiter to become closed.
connError represents an HTTP/2 ConnectionError error code, along
with a string (for debugging) explaining why.
Errors of this type are only returned by the frame parser functions
and converted into ConnectionError(Code), after stashing away
the Reason into the Framer's errDetail field, accessible via
the (*Framer).ErrorDetail method.
// the ConnectionError error code
// additional reason
( T) Error() string
T : error
dataBuffer is an io.ReadWriter backed by a list of data chunks.
Each dataBuffer is used to read DATA frames on a single stream.
The buffer is divided into chunks so the server can limit the
total memory used by a single connection without limiting the
request body size on any single stream.
chunks[][]byte
// we expect at least this many bytes in future Write calls (ignored if <= 0)
// next byte to read is chunks[0][r]
// total buffered bytes
// next byte to write is chunks[len(chunks)-1][w]
Len returns the number of bytes of the unread portion of the buffer.
Read copies bytes from the buffer into p.
It is an error to read when no data is available.
Write appends p to the buffer.
(*T) bytesFromFirstChunk() []byte(*T) lastChunkOrAlloc(want int64) []byte
*T : github.com/go-git/go-git/v5/plumbing/protocol/packp/sideband.Progress
*T : github.com/jbenet/go-context/io.Reader
*T : github.com/jbenet/go-context/io.Writer
*T : io.Reader
*T : io.ReadWriter
*T : io.Writer
*T : pipeBuffer
*T : github.com/aws/aws-sdk-go/aws/corehandlers.lener
*T : net/http.http2pipeBuffer
dialCall is an in-flight Transport dial call to a host.
// closed when done
// valid after done is closed
p*clientConnPool
// valid after done is closed
run in its own goroutine.
flow is the flow control window's size.
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.
n is the number of DATA bytes we're allowed to send.
A flow is kept both on a conn and a per-stream.
add adds n bytes (positive or negative) to the flow control window.
It returns false if the sum would exceed 2^31-1.
(*T) available() int32(*T) setConnFlow(cf *flow)(*T) take(n int32)
a frameParser parses a frame given its FrameHeader and payload
bytes. The length of payload will always equal fh.Length (which
might be 0).
func typeFrameParser(t FrameType) frameParser
frameWriteResult is the message passed from writeFrameAsync to the serve goroutine.
// result of the writeFrame call
// what was written (or attempted)
A gate lets two goroutines coordinate their activities.
( T) Done()( T) Wait()
6.9.1 The Flow Control Window
"If a sender receives a WINDOW_UPDATE that causes a flow control
window to exceed this maximum it MUST terminate either the stream
or the connection, as appropriate. For streams, [...]; for the
connection, a GOAWAY frame with a FLOW_CONTROL_ERROR code."
( T) Error() string
T : error
incomparable is a zero-width, non-comparable type. Adding it to a struct
makes that struct also non-comparable, and generally doesn't add
any size (as long as it's first).
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.
( T) Error() string( T) IsHTTP2NoCachedConnError()
T : error
noDialClientConnPool is an implementation of http2.ClientConnPool
which never dials. We let the HTTP/1.1 client dial and use its TLS
connection instead.
clientConnPool*clientConnPool
// in-flight addConnIfNeede calls
TODO: add support for sharing conns based on cert names
(e.g. share conn for googleapis.com and appspot.com)
// key is host:port
// currently in-flight dials
clientConnPool.keysmap[*ClientConn][]string
// TODO: maybe switch to RWMutex
clientConnPool.t*Transport( T) GetClientConn(req *http.Request, addr string) (*ClientConn, error)( T) MarkDead(cc *ClientConn)
addConnIfNeeded makes a NewClientConn out of c if a connection for key doesn't
already exist. It coalesces concurrent calls with the same key.
This is used by the http1 Transport code when it creates a new connection. Because
the http1 Transport doesn't de-dup TCP dials to outbound hosts (because it doesn't know
the protocol), it can get into a situation where it has multiple TLS connections.
This code decides which ones live or die.
The return value used is whether c was used.
c is never closed.
p.mu must be held
( T) closeIdleConnections()( T) getClientConn(req *http.Request, addr string, dialOnMiss bool) (*ClientConn, error)
requires p.mu is held.
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.
T : ClientConnPool
T : clientConnPoolIdleCloser
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)
Transport*Transport
AllowHTTP, if true, permits HTTP/2 requests using the insecure,
plain-text "http" scheme. Note that this does not enable h2c support.
ConnPool optionally specifies an alternate connection pool to use.
If nil, the default is used.
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.
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.
MaxHeaderListSize is the http2 SETTINGS_MAX_HEADER_LIST_SIZE to
send in the initial settings frame. It is how many bytes
of response headers are allowed. Unlike the http2 spec, zero here
means to use a default limit (currently 10MB). If you actually
want to advertise an unlimited value to the peer, Transport
interprets the highest possible value here (0xffffffff or 1<<32-1)
to mean no limit.
PingTimeout is the timeout after which the connection will be closed
if a response to Ping is not received.
Defaults to 15s.
ReadIdleTimeout is the timeout after which a health check using ping
frame will be carried out if no frame is received on the connection.
Note that a ping response will is considered a received frame, so if
there is no other traffic on the connection, the health check will
be performed every ReadIdleTimeout interval.
If zero, no health check is performed.
StrictMaxConcurrentStreams controls whether the server's
SETTINGS_MAX_CONCURRENT_STREAMS should be respected
globally. If false, new TCP connections are created to the
server as needed to keep each under the per-connection
SETTINGS_MAX_CONCURRENT_STREAMS limit. If true, the
server's SETTINGS_MAX_CONCURRENT_STREAMS is interpreted as
a global limit and callers of RoundTrip block when needed,
waiting for their turn.
TLSClientConfig specifies the TLS configuration to use with
tls.Client. If nil, the default configuration is used.
Transport.connPoolOncesync.Once
// non-nil version of ConnPool
t1, if non-nil, is the standard library Transport using
this transport. Its settings are used (but not its
RoundTrip method, etc).
CloseIdleConnections closes any connections which were previously
connected from previous requests but are now sitting idle.
It does not interrupt any connections currently in use.
( T) NewClientConn(c net.Conn) (*ClientConn, error)( T) RoundTrip(req *http.Request) (*http.Response, error)
RoundTripOpt is like RoundTrip, but takes options.
( T) connPool() ClientConnPool( T) dialClientConn(addr string, singleUse bool) (*ClientConn, error)( T) dialTLS() func(string, string, *tls.Config) (net.Conn, error)( T) dialTLSDefault(network, addr string, cfg *tls.Config) (net.Conn, error)( T) disableCompression() bool
disableKeepAlives reports whether connections should be closed as
soon as possible after handling the first request.
( T) expectContinueTimeout() time.Duration( T) getBodyWriterState(cs *clientStream, body io.Reader) (s bodyWriterState)( T) idleConnTimeout() time.Duration( T) initConnPool()( T) logf(format string, args ...interface{})( T) maxHeaderListSize() uint32( T) newClientConn(c net.Conn, singleUse bool) (*ClientConn, error)( T) newTLSConfig(host string) *tls.Config( T) pingTimeout() time.Duration( T) vlogf(format string, args ...interface{})
T : net/http.RoundTripper
T : net/http.h2Transport
T : net/http/httptest.closeIdleTransport
func registerHTTPSProtocol(t *http.Transport, rt noDialH2RoundTripper) (err error)
pipe is a goroutine-safe io.Reader/io.Writer pair. It's like
io.Pipe except there are no PipeReader/PipeWriter halves, and the
underlying buffer is an interface. (io.Pipe is always unbuffered)
// nil when done reading
// immediate read error (caller doesn't see rest of b)
// c.L lazily initialized to &p.mu
// closed on error
// read error once empty. non-nil means closed.
musync.Mutex
// optional code to run in Read before error
// bytes unread when done
BreakWithError causes the next Read (waking up a current blocked
Read if needed) to return the provided err immediately, without
waiting for unread data.
CloseWithError causes the next Read (waking up a current blocked
Read if needed) to return the provided err after all data has been
read.
The error must be non-nil.
Done returns a channel which is closed if and when this pipe is closed
with CloseWithError.
Err returns the error (if any) first set by BreakWithError or CloseWithError.
(*T) Len() int
Read waits until data is available and copies bytes
from the buffer into p.
Write copies bytes from p into the buffer and wakes a reader.
It is an error to write more data than the buffer can hold.
requires p.mu be held.
(*T) closeWithError(dst *error, err error, fn func())
closeWithErrorAndCode is like CloseWithError but also sets some code to run
in the caller's goroutine before returning the error.
*T : github.com/go-git/go-git/v5/plumbing/protocol/packp/sideband.Progress
*T : github.com/jbenet/go-context/io.Reader
*T : github.com/jbenet/go-context/io.Writer
*T : io.Reader
*T : io.ReadWriter
*T : io.Writer
*T : pipeBuffer
*T : github.com/aws/aws-sdk-go/aws/corehandlers.lener
*T : net/http.http2pipeBuffer
priorityNode is a node in an HTTP/2 priority tree.
Each node is associated with a single stream ID.
See RFC 7540, Section 5.3.
// number of bytes written by this node, or 0 if closed
// id of the stream, or 0 for the root of the tree
// start of the kids list
// doubly-linked list of siblings
These links form the priority tree.
// doubly-linked list of siblings
// queue of pending frames to write
// open | closed | idle
// sum(node.bytes) of all nodes in this subtree
// the actual weight is weight+1, so the value is in [1,256]
(*T) addBytes(b int64)(*T) setParent(parent *priorityNode)
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).
lists of nodes that have been closed or are idle, but are kept in
the tree for improved prioritization. When the lengths exceed either
maxClosedNodesInTree or maxIdleNodesInTree, old nodes are discarded.
enableWriteThrottlebool
lists of nodes that have been closed or are idle, but are kept in
the tree for improved prioritization. When the lengths exceed either
maxClosedNodesInTree or maxIdleNodesInTree, old nodes are discarded.
From the config.
maxID is the maximum stream id in nodes.
maxIdleNodesInTreeint
nodes maps stream ids to priority tree nodes.
pool of empty queues for reuse.
root is the root of the priority tree, where root.id = 0.
The root queues control frames that are not associated with any stream.
tmp is scratch space for priorityNode.walkReadyInOrder to reduce allocations.
writeThrottleLimitint32(*T) AdjustStream(streamID uint32, priority PriorityParam)(*T) CloseStream(streamID uint32)(*T) OpenStream(streamID uint32, options OpenStreamOptions)(*T) Pop() (wr FrameWriteRequest, ok bool)(*T) Push(wr FrameWriteRequest)(*T) addClosedOrIdleNode(list *[]*priorityNode, maxSize int, n *priorityNode)(*T) removeNode(n *priorityNode)
*T : WriteScheduler
errerror
// valid until readMore is called
readMore should be called once the consumer no longer needs or
retains f. After readMore, f is invalid and more frames can be
read.
requestBody is the Handler's Request.Body type.
Read and Close may be called concurrently.
// for use by Close only
conn*serverConn
// need to send a 100-continue
// non-nil if we have a HTTP entity message body
// for use by Read only
stream*stream(*T) Close() error(*T) Read(p []byte) (n int, err error)
*T : github.com/jbenet/go-context/io.Reader
*T : io.Closer
*T : io.ReadCloser
*T : io.Reader
responseWriter is the http.ResponseWriter implementation. It's
intentionally small (1 pointer wide) to minimize garbage. The
responseWriterState pointer inside is zeroed at the end of a
request (in handlerDone) and calls on the responseWriter thereafter
simply crash (caller's mistake), but the much larger responseWriterState
and buffers are reused between multiple requests.
rws*responseWriterState(*T) CloseNotify() <-chan bool(*T) Flush()(*T) Header() http.Header(*T) Push(target string, opts *http.PushOptions) 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)
(*T) WriteHeader(code int)(*T) WriteString(s string) (n int, err error)(*T) handlerDone()
either dataB or dataS is non-zero.
*T : github.com/go-git/go-git/v5/plumbing/protocol/packp/sideband.Progress
*T : github.com/jbenet/go-context/io.Writer
*T : io.StringWriter
*T : io.Writer
*T : net/http.CloseNotifier
*T : net/http.Flusher
*T : net/http.Pusher
*T : net/http.ResponseWriter
*T : stringWriter
*T : net/http.http2stringWriter
*T : net/http/httputil.writeFlusher
// to close at end of request, if DATA frames didn't
TODO: adjust buffer writing sizes based on server config, frame size updates from peer, etc
// writing to a chunkWriter{this *responseWriterState}
// nil until first used
// guards closeNotifierCh
conn*serverConn
// a Write failed; don't reuse this responseWriterState
// handler has finished
mutated by http.Handler goroutine:
// nil until called
req*http.Request
// non-zero if handler set a Content-Length header
// have we sent the header frame?
// snapshot of handlerHeader at WriteHeader time
// status code passed to WriteHeader
immutable within a request:
// set in writeChunk
wroteBytesint64
// WriteHeader called (explicitly or implicitly). Not necessarily sent to user yet.
declareTrailer is called for each Trailer header when the
response header is written. It notes that a header will need to be
written in the trailers at the end of the response.
(*T) hasNonemptyTrailers() bool(*T) hasTrailers() bool
promoteUndeclaredTrailers permits http.Handlers to set trailers
after the header has already been flushed. Because the Go
ResponseWriter interface has no way to set Trailers (only the
Header), and because we didn't want to expand the ResponseWriter
interface, and because nobody used trailers, and because RFC 7230
says you SHOULD (but not must) predeclare any trailers in the
header, the official ResponseWriter rules said trailers in Go must
be predeclared, and then we reuse the same ResponseWriter.Header()
map to mean both Headers and Trailers. When it's time to write the
Trailers, we pick out the fields of Headers that were declared as
trailers. That worked for a while, until we found the first major
user of Trailers in the wild: gRPC (using them only over http2),
and gRPC libraries permit setting trailers mid-stream without
predeclaring them. So: change of plans. We still permit the old
way, but we also permit this hack: if a Header() key begins with
"Trailer:", the suffix of that key is a Trailer. Because ':' is an
invalid token byte anyway, there is no ambiguity. (And it's already
filtered out) It's mildly hacky, but not terrible.
This method runs after the Handler is done and promotes any Header
fields to be trailers.
writeChunk writes chunks from the bufio.Writer. But because
bufio.Writer may bypass its chunking, sometimes p may be
arbitrarily large.
writeChunk is also responsible (on the first chunk) for sending the
HEADER response.
(*T) writeHeader(code int)
// our SETTINGS_MAX_CONCURRENT_STREAMS advertised the client
baseCtxcontext.Context
// from handlers -> serve
// writing to conn
// http2-lower-case -> Go-Canonical-Case
// SETTINGS_MAX_CONCURRENT_STREAMS from client (our PUSH_PROMISE limit)
connnet.Conn
// number of open streams initiated by the client
// number of open streams initiated by server push
// closed when serverConn.serve ends
// conn-wide (not stream-specific) outbound flow control
framer*FramergoAwayCodeErrCodehandlerhttp.HandlerheaderTableSizeuint32
Owned by the writeFrameAsync goroutine:
hpackEncoder*hpack.Encoderhs*http.Server
// nil if unused
// whether we're in the scheduleFrameWrite loop
// we've started to or sent GOAWAY
// conn-wide inbound flow control
initialStreamSendWindowSizeint32
// max ever seen from client (odd), or 0 if there have been no client requests
maxFrameSizeint32
// ID of the last push promise (even), or 0 if there have been no pushes
// we need to schedule a GOAWAY frame write
needToSendSettingsAckbool
// last frame write wasn't a flush
// zero means unknown (default)
pushEnabledbool
// control frames in the writeSched queue
// written by serverConn.readFrames
remoteAddrStrstring
// got the initial SETTINGS frame after the preface
Everything following is owned by the serve loop; use serveG.check():
// used to verify funcs are on serve()
// misc messages & code to send to / run on the serve loop
Used by startGracefulShutdown.
// nil until used
Immutable:
streamsmap[uint32]*stream
// shared by all handlers, like net/http
// how many SETTINGS have we sent without ACKs?
// from handlers -> serve
writeSchedWriteScheduler
// started writing a frame (on serve goroutine or separate)
// started a frame on its own goroutine but haven't heard back on wroteFrameCh
// from writeFrameAsync -> serve, tickles more frame writes
(*T) CloseConn() error(*T) Flush() error(*T) Framer() *Framer(*T) HeaderEncoder() (*hpack.Encoder, *bytes.Buffer)(*T) awaitGracefulShutdown(sharedCh <-chan struct{}, privateCh chan struct{})(*T) canonicalHeader(v string) string(*T) closeAllStreamsOnConnClose()(*T) closeStream(st *stream, err error)(*T) condlogf(err error, format string, args ...interface{})(*T) curOpenStreams() uint32(*T) goAway(code ErrCode)(*T) logf(format string, args ...interface{})(*T) maxHeaderListSize() uint32(*T) newStream(id, pusherID uint32, state streamState) *stream(*T) newWriterAndRequest(st *stream, f *MetaHeadersFrame) (*responseWriter, *http.Request, error)(*T) newWriterAndRequestNoBody(st *stream, rp requestParam) (*responseWriter, *http.Request, error)(*T) noteBodyRead(st *stream, n int)
called from handler goroutines.
Notes that the handler for the given stream ID read n bytes of its body
and schedules flow control tokens to be sent.
(*T) notePanic()(*T) onIdleTimer()(*T) onSettingsTimer()(*T) onShutdownTimer()(*T) processData(f *DataFrame) error(*T) processFrame(f Frame) error
processFrameFromReader processes the serve loop's read from readFrameCh from the
frame-reading goroutine.
processFrameFromReader returns whether the connection should be kept open.
(*T) processGoAway(f *GoAwayFrame) error(*T) processHeaders(f *MetaHeadersFrame) error(*T) processPing(f *PingFrame) error(*T) processPriority(f *PriorityFrame) error(*T) processResetStream(f *RSTStreamFrame) error(*T) processSetting(s Setting) error(*T) processSettingInitialWindowSize(val uint32) error(*T) processSettings(f *SettingsFrame) error(*T) processWindowUpdate(f *WindowUpdateFrame) error
readFrames is the loop that reads incoming frames.
It takes care to only read one frame at a time, blocking until the
consumer is done with the frame.
It's run on its own goroutine.
readPreface reads the ClientPreface greeting from the peer or
returns errPrefaceTimeout on timeout, or an error if the greeting
is invalid.
(*T) rejectConn(err ErrCode, debug string)(*T) resetStream(se StreamError)
Run on its own goroutine.
scheduleFrameWrite tickles the frame writing scheduler.
If a frame is already being written, nothing happens. This will be called again
when the frame is done being written.
If a frame isn't being written and we need to send one, the best frame
to send is selected by writeSched.
If a frame isn't being written and there's nothing else to send, we
flush the write buffer.
(*T) sendServeMsg(msg interface{})
st may be nil for conn-level
st may be nil for conn-level
(*T) serve()
setConnState calls the net/http ConnState hook for this connection, if configured.
Note that the net/http package does StateNew and StateClosed for us.
There is currently no plan for StateHijacked or hijacking HTTP/2 connections.
(*T) shutDownIn(d time.Duration)
startFrameWrite starts a goroutine to write wr (in a separate
goroutine since that might block on the network), and updates the
serve goroutine's state about the world, updated from info in wr.
startGracefulShutdown gracefully shuts down a connection. This
sends GOAWAY with ErrCodeNo to tell the client we're gracefully
shutting down. The connection isn't closed until all current
streams are done.
startGracefulShutdown returns immediately; it does not wait until
the connection has shut down.
(*T) startGracefulShutdownInternal()(*T) startPush(msg *startPushRequest)(*T) state(streamID uint32) (streamState, *stream)(*T) stopShutdownTimer()(*T) vlogf(format string, args ...interface{})
called from handler goroutines.
writeDataFromHandler writes DATA response frames from a handler on
the given stream.
writeFrame schedules a frame to write and sends it if there's nothing
already being written.
There is no pushback here (the serve goroutine never blocks). It's
the http.Handlers that block, waiting for their previous frames to
make it onto the wire
If you're not on the serve goroutine, use writeFrameFromHandler instead.
writeFrameAsync runs in its own goroutine and writes a single frame
and then reports when it's done.
At most one goroutine can be running writeFrameAsync at a time per
serverConn.
writeFrameFromHandler sends wr to sc.wantWriteFrameCh, but aborts
if the connection has gone away.
This must not be run from the serve goroutine itself, else it might
deadlock writing to sc.wantWriteFrameCh (which is only mildly
buffered and is read by serve itself). If you're on the serve
goroutine, call writeFrame instead.
called from handler goroutines.
h may be nil.
wroteFrame is called on the serve goroutine with the result of
whatever happened on writeFrameAsync.
*T : writeContext
// owned by sorter
Keys returns the sorted keys of h.
The returned slice is only valid until s used again or returned to
its pool.
(*T) Len() int(*T) Less(i, j int) bool(*T) SortStrings(ss []string)(*T) Swap(i, j int)
*T : sort.Interface
*T : github.com/aws/aws-sdk-go/aws/corehandlers.lener
stream represents a stream. This is the minimal metadata needed by
the serve goroutine. Most of the actual stream state is owned by
the http.Handler's goroutine in the responseWriter. Because the
responseWriter's responseWriterState is recycled at the end of a
handler, this struct intentionally has no pointer to the
*responseWriter{,State} itself, as the Handler ending nils out the
responseWriter's state field.
// non-nil if expecting DATA frames
owned by serverConn's serve loop:
// body bytes seen so far
cancelCtxfunc()ctxcontext.Context
// closed wait stream transitions to closed state
// or -1 if undeclared
// limits writing from Handler to client
// HEADER frame for trailers was seen
iduint32
// what the client is allowed to POST/etc to us
// handler's Request.Trailer
// RST_STREAM queued for write; set by sc.resetStream
immutable:
statestreamState
// accumulated trailers
// nil if unused
// whether we wrote headers (not status 100)
copyTrailersToHandlerRequest is run in the Handler's goroutine in
its Request.Body.Read just before it gets io.EOF.
endStream closes a Request.Body's pipe. It is called when a DATA
frame says a request body is over (or after trailers).
isPushed reports whether the stream is server-initiated.
onWriteTimeout is run on its own goroutine (from time.AfterFunc)
when the stream's WriteTimeout has fired.
(*T) processTrailerHeaders(f *MetaHeadersFrame) error
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.
cs*clientStream( T) Close() error( T) Read(p []byte) (n int, err error)
T : github.com/jbenet/go-context/io.Reader
T : io.Closer
T : io.ReadCloser
T : io.Reader
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.
( T) CloseConn() error( T) Flush() error( T) Framer() *Framer
HeaderEncoder returns an HPACK encoder that writes to the
returned buffer.
*serverConn
func splitHeaderBlock(ctx writeContext, headerBlock []byte, fn func(ctx writeContext, frag []byte, firstFrag, lastFrag bool) error) error
func StreamError.writeFrame(ctx writeContext) error
writeQueue is used by implementations of WriteScheduler.
s[]FrameWriteRequest
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.
(*T) empty() bool(*T) push(wr FrameWriteRequest)(*T) shift() FrameWriteRequest
get returns an empty writeQueue.
put inserts an unused writeQueue into the pool.
Package-Level Functions (total 84, in which 7 are exported)
ConfigureServer adds HTTP/2 support to a net/http Server.
The configuration conf may be nil.
ConfigureServer must be called before s begins serving.
ConfigureTransport configures a net/http HTTP/1 Transport to use HTTP/2.
It returns an error if t1 has already been HTTP/2-enabled.
Use ConfigureTransports instead to configure the HTTP/2 Transport.
ConfigureTransports configures a net/http HTTP/1 Transport to use HTTP/2.
It returns a new HTTP/2 Transport for further configuration.
It returns an error if t1 has already been HTTP/2-enabled.
NewFramer returns a Framer that writes frames to w and reads them from r.
NewPriorityWriteScheduler constructs a WriteScheduler that schedules
frames by following HTTP/2 priorities as described in RFC 7540 Section 5.3.
If cfg is nil, default options are used.
NewRandomWriteScheduler constructs a WriteScheduler that ignores HTTP/2
priorities. Control frames like SETTINGS and PING are written before DATA
frames, but if no control frames are queued and multiple streams have queued
HEADERS or DATA frames, Pop selects a ready stream arbitrarily.
ReadFrameHeader reads 9 bytes from r and returns a FrameHeader.
Most users should use Framer.ReadFrame instead.
actualContentLength returns a sanitized version of
req.ContentLength, where 0 actually means zero (not unknown) and -1
means unknown.
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.
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.
bodyAllowedForStatus reports whether a given response status code
permits a body. See RFC 7230, section 3.3.
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.
h1ServerKeepAlivesDisabled reports whether hs has its keep-alives
disabled. See comments on h1ServerShutdownChan above for why
the code is written this way.
isBadCipher reports whether the cipher is blacklisted by the HTTP/2 spec.
References:
https://tools.ietf.org/html/rfc7540#appendix-A
Reject cipher suites from Appendix A.
"This list includes those cipher suites that do not
offer an ephemeral key exchange and those that are
based on the TLS null, stream or block cipher type"
isClosedConnError reports whether err is an error from use of a closed
network connection.
isConnectionCloseRequest reports whether req should use its own
connection for a single request and then close the connection.
isNoCachedConnError reports whether err is of type noCachedConnError
or its equivalent renamed type in net/http2's h2_bundle.go. Both types
may coexist in the same running program.
shouldRetryRequest is called by RoundTrip when a request fails to get
response headers. It is always called with a non-nil error.
It returns either a request to retry (either the same request, or a
modified clone), or an error if the request can't be replayed.
shouldSendReqContentLength reports whether the http2.Transport should send
a "content-length" request header. This logic is basically a copy of the net/http
transferWriter.shouldSendContentLength.
The contentLength is the corrected contentLength (so 0 means actually 0, not unknown).
-1 means unknown.
splitHeaderBlock splits headerBlock into fragments so that each fragment fits
in a single frame, then calls fn for each fragment. firstFrag/lastFrag are true
for the first/last fragment, respectively.
validPseudoPath reports whether v is a valid :path pseudo-header
value. It must be either:
*) a non-empty string starting with '/'
*) the string '*', for OPTIONS requests.
For now this is only used a quick check for deciding when to clean
up Opaque URLs before sending requests from the Transport.
See golang.org/issue/16847
We used to enforce that the path also didn't start with "//", but
Google's GFE accepts such paths and Chrome sends them, so ignore
that part of the spec. See golang.org/issue/19103.
validWireHeaderFieldName reports whether v is a valid header field
name (key). See httpguts.ValidHeaderName for the base rules.
Further, http2 says:
"Just as in HTTP/1.x, header field names are strings of ASCII
characters that are compared in a case-insensitive
fashion. However, header field names MUST be converted to
lowercase prior to their encoding in HTTP/2. "
writeEndsStream reports whether w writes a frame that will transition
the stream to a half-closed local state. This returns false for RST_STREAM,
which closes the entire stream (not just the local half).
Package-Level Variables (total 68, in which 6 are exported)
From http://httpwg.org/specs/rfc7540.html#rfc.section.8.1.2.2
Buffer chunks are allocated from a pool to reduce pressure on GC.
The maximum wasted space per dataBuffer is 2x the largest size class,
which happens when the dataBuffer has multiple chunks and there is
one unread byte in both the first and last chunks. We use a few size
classes to minimize overheads for servers that typically receive very
small request bodies.
TODO: Benchmark to determine if the pools are necessary. The GC may have
improved enough that we can instead allocate chunks like this:
make([]byte, max(16<<10, expectedBytesRemaining))
Buffer chunks are allocated from a pool to reduce pressure on GC.
The maximum wasted space per dataBuffer is 2x the largest size class,
which happens when the dataBuffer has multiple chunks and there is
one unread byte in both the first and last chunks. We use a few size
classes to minimize overheads for servers that typically receive very
small request bodies.
TODO: Benchmark to determine if the pools are necessary. The GC may have
improved enough that we can instead allocate chunks like this:
make([]byte, max(16<<10, expectedBytesRemaining))
errHandlerPanicked is the error given to any callers blocked in a read from
Request.Body when the main goroutine panics. Since most handlers read in the
main ServeHTTP goroutine, this will show up rarely.
After sending GOAWAY with an error code (non-graceful shutdown), the
connection will close after goAwayTimeout.
If we close the connection immediately after sending GOAWAY, there may
be unsent data in our kernel receive buffer, which will cause the kernel
to send a TCP RST on close() instead of a FIN. This RST will abort the
connection immediately, whether or not the client had received the GOAWAY.
Ideally we should delay for at least 1 RTT + epsilon so the client has
a chance to read the GOAWAY and stop sending messages. Measuring RTT
is hard, so we approximate with 1 second. See golang.org/issue/18701.
This is a var so it can be shorter in tests, where all requests uses the
loopback interface making the expected RTT very small.
TODO: configurable?
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
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.
HTTP/2 stream states.
See http://tools.ietf.org/html/rfc7540#section-5.1.
For simplicity, the server code merges "reserved (local)" into
"half-closed (remote)". This is one less state transition to track.
The only downside is that we send PUSH_PROMISEs slightly less
liberally than allowable. More discussion here:
https://lists.w3.org/Archives/Public/ietf-http-wg/2016JulSep/0599.html
"reserved (remote)" is omitted since the client code does not
support server push.
HTTP/2 stream states.
See http://tools.ietf.org/html/rfc7540#section-5.1.
For simplicity, the server code merges "reserved (local)" into
"half-closed (remote)". This is one less state transition to track.
The only downside is that we send PUSH_PROMISEs slightly less
liberally than allowable. More discussion here:
https://lists.w3.org/Archives/Public/ietf-http-wg/2016JulSep/0599.html
"reserved (remote)" is omitted since the client code does not
support server push.
HTTP/2 stream states.
See http://tools.ietf.org/html/rfc7540#section-5.1.
For simplicity, the server code merges "reserved (local)" into
"half-closed (remote)". This is one less state transition to track.
The only downside is that we send PUSH_PROMISEs slightly less
liberally than allowable. More discussion here:
https://lists.w3.org/Archives/Public/ietf-http-wg/2016JulSep/0599.html
"reserved (remote)" is omitted since the client code does not
support server push.
HTTP/2 stream states.
See http://tools.ietf.org/html/rfc7540#section-5.1.
For simplicity, the server code merges "reserved (local)" into
"half-closed (remote)". This is one less state transition to track.
The only downside is that we send PUSH_PROMISEs slightly less
liberally than allowable. More discussion here:
https://lists.w3.org/Archives/Public/ietf-http-wg/2016JulSep/0599.html
"reserved (remote)" is omitted since the client code does not
support server push.
HTTP/2 stream states.
See http://tools.ietf.org/html/rfc7540#section-5.1.
For simplicity, the server code merges "reserved (local)" into
"half-closed (remote)". This is one less state transition to track.
The only downside is that we send PUSH_PROMISEs slightly less
liberally than allowable. More discussion here:
https://lists.w3.org/Archives/Public/ietf-http-wg/2016JulSep/0599.html
"reserved (remote)" is omitted since the client code does not
support server push.
transportDefaultConnFlow is how many connection-level flow control
tokens we give the server at start-up, past the default 64k.
transportDefaultStreamFlow is how many stream-level flow
control tokens we announce to the peer, and how many bytes
we buffer per stream.
transportDefaultStreamMinRefresh is the minimum number of bytes we'll send
a stream-level WINDOW_UPDATE for at a time.
The pages are generated with Goldsv0.3.2-preview. (GOOS=darwin GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds.