ClientConnPool manages a pool of HTTP/2 client connections.
Deprecated: To create a custom connection pool, implement
[http.RoundTripper]. Use [http.Transport.NewClientConn]
to create connections for the pool. GetClientConn returns a specific HTTP/2 connection (usually
a TLS-TCP connection) to an HTTP/2 server. On success, the
returned ClientConn accounts for the upcoming RoundTrip
call, so the caller should not omit it. If the caller needs
to, ClientConn.RoundTrip can be called with a bogus
new(http.Request) to release the stream reservation.( ClientConnPool) MarkDead(*ClientConn)
func (*Transport).roundTripViaPool(req *http.Request, opt RoundTripOpt, pool ClientConnPool) (*http.Response, error)
ClientConnState describes the state of a ClientConn.
Deprecated: Use [http.ClientConn] instead. Closed is whether the connection is closed. Closing is whether the connection is in the process of
closing. It may be closing due to shutdown, being a
single-use connection, being marked as DoNotReuse, or
having received a GOAWAY frame. LastIdle, if non-zero, is when the connection last
transitioned to idle state. MaxConcurrentStreams is how many concurrent streams the
peer advertised as acceptable. Zero means no SETTINGS
frame has been received yet. StreamsActive is how many streams are active. StreamsPending is how many requests have been sent in excess
of the peer's advertised MaxConcurrentStreams setting and
are waiting for other streams to complete. StreamsReserved is how many streams have been reserved via
ClientConn.ReserveNewRequest.
func (*ClientConn).State() ClientConnState
func (*ClientConn).state() ClientConnState
ConnectionError is an error that results in the termination of the
entire connection.( ConnectionError) Error() string
ConnectionError : error
A ContinuationFrame is used to continue a sequence of header block fragments.
See https://httpwg.org/specs/rfc7540.html#rfc.section.6.10FrameHeaderFrameHeader 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 FrameheaderFragBuf[]byte Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.(*ContinuationFrame) HeaderBlockFragment() []byte(*ContinuationFrame) HeadersEnded() bool( ContinuationFrame) String() string(*ContinuationFrame) checkValid()(*ContinuationFrame) invalidate()( ContinuationFrame) writeDebug(buf *bytes.Buffer)
*ContinuationFrame : Frame
ContinuationFrame : expvar.Var
ContinuationFrame : fmt.Stringer
*ContinuationFrame : headersEnder
*ContinuationFrame : headersOrContinuation
ContinuationFrame : context.stringer
*ContinuationFrame : net/http/internal/http2.headersEnder
*ContinuationFrame : net/http/internal/http2.headersOrContinuation
ContinuationFrame : runtime.stringer
A DataFrame conveys arbitrary, variable-length sequences of octets
associated with a stream.
See https://httpwg.org/specs/rfc7540.html#rfc.section.6.1FrameHeaderFrameHeader 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.(*DataFrame) StreamEnded() bool( DataFrame) String() string(*DataFrame) checkValid()(*DataFrame) invalidate()( DataFrame) writeDebug(buf *bytes.Buffer)
*DataFrame : Frame
DataFrame : expvar.Var
DataFrame : fmt.Stringer
*DataFrame : streamEnder
DataFrame : context.stringer
*DataFrame : net/http/internal/http2.streamEnder
DataFrame : 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. countError is a non-nil func that's called on a frame parse
error with some unique error path token. It's initialized
from Transport.CountError or Server.CountError. // only use for logging written writesdebugFramerBuf*bytes.BufferdebugReadLoggerffunc(string, ...interface{})debugWriteLoggerffunc(string, ...interface{})errDetailerror // nil if frames aren't reused (default) TODO: let getReadBuf be configurable, and use a less memory-pinning
allocator in server.go to minimize memory pinned for many idle conns.
Will probably also need to make frame invalidation have a hook too.headerBuf[9]bytelastFrameFrame lastFrameType holds the type of the last frame for verifying frame order. lastHeaderStream is non-zero if the last frame was an
unfinished HEADERS/CONTINUATION.logReadsboollogWritesboolmaxReadSizeuint32 // zero means unlimited; TODO: implementrio.Reader // cache for default getReadBufwio.Writerwbuf[]byte ErrorDetail returns a more detailed error of the last error
returned by Framer.ReadFrame. For instance, if ReadFrame
returns a StreamError with code PROTOCOL_ERROR, ErrorDetail
will say exactly what was invalid. ErrorDetail is not guaranteed
to return a non-nil value and like the rest of the http2 package,
its return value is not protected by an API compatibility promise.
ErrorDetail is reset after the next call to ReadFrame. ReadFrame reads a single frame. The returned Frame is only valid
until the next call to ReadFrame or ReadFrameBodyForHeader.
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.
If ReadFrame returns an error and a non-nil Frame, the Frame's StreamID
indicates the stream responsible for the error. ReadFrameForHeader reads the payload for the frame with the given FrameHeader.
It behaves identically to ReadFrame, other than not checking the maximum
frame size. ReadFrameHeader reads the header of the next frame.
It reads the 9-byte fixed frame header, and does not read any portion of the
frame payload. The caller is responsible for consuming the payload, either
with ReadFrameForHeader or directly from the Framer's io.Reader.
If the frame is larger than previously set with SetMaxReadFrameSize, it
returns the frame header and ErrFrameTooLarge.
If the returned FrameHeader.StreamID is non-zero, it indicates the stream
responsible for the error. 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.(*Framer) 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.(*Framer) 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. WritePriorityUpdate writes a PRIORITY_UPDATE 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.(*Framer) endWrite() error(*Framer) logWrite()(*Framer) maxHeaderListSize() uint32(*Framer) 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.(*Framer) startWrite(ftype FrameType, flags Flags, streamID uint32) startWriteDataPadded is WriteDataPadded, but only writes the frame to the Framer's internal buffer.
The caller should call endWrite to flush the frame to the underlying writer.(*Framer) writeByte(v byte)(*Framer) writeBytes(v []byte)(*Framer) writeUint16(v uint16)(*Framer) writeUint32(v uint32)
func NewFramer(w io.Writer, r io.Reader) *Framer
A GoAwayFrame informs the remote peer to stop creating streams on this connection.
See https://httpwg.org/specs/rfc7540.html#rfc.section.6.8ErrCodeErrCodeFrameHeaderFrameHeader 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.( GoAwayFrame) String() string(*GoAwayFrame) checkValid()(*GoAwayFrame) invalidate()( GoAwayFrame) writeDebug(buf *bytes.Buffer)
*GoAwayFrame : Frame
GoAwayFrame : expvar.Var
GoAwayFrame : fmt.Stringer
GoAwayFrame : context.stringer
GoAwayFrame : runtime.stringer
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(*HeadersFrame) HasPriority() bool Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.(*HeadersFrame) HeaderBlockFragment() []byte(*HeadersFrame) HeadersEnded() bool(*HeadersFrame) StreamEnded() bool( HeadersFrame) String() string(*HeadersFrame) checkValid()(*HeadersFrame) invalidate()( HeadersFrame) writeDebug(buf *bytes.Buffer)
*HeadersFrame : Frame
HeadersFrame : expvar.Var
HeadersFrame : fmt.Stringer
*HeadersFrame : headersEnder
*HeadersFrame : headersOrContinuation
*HeadersFrame : streamEnder
HeadersFrame : context.stringer
*HeadersFrame : net/http/internal/http2.headersEnder
*HeadersFrame : net/http/internal/http2.headersOrContinuation
*HeadersFrame : net/http/internal/http2.streamEnder
HeadersFrame : runtime.stringer
func (*Framer).readMetaFrame(hf *HeadersFrame) (Frame, 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( MetaHeadersFrame) HasPriority() bool Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.( MetaHeadersFrame) HeaderBlockFragment() []byte( MetaHeadersFrame) 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.( MetaHeadersFrame) StreamEnded() bool( MetaHeadersFrame) String() string(*MetaHeadersFrame) checkPseudos() error( MetaHeadersFrame) checkValid()( MetaHeadersFrame) invalidate()(*MetaHeadersFrame) rfc9218Priority(priorityAware bool) (p PriorityParam, priorityAwareAfter, hasIntermediary bool)( MetaHeadersFrame) writeDebug(buf *bytes.Buffer)
MetaHeadersFrame : Frame
MetaHeadersFrame : expvar.Var
MetaHeadersFrame : fmt.Stringer
MetaHeadersFrame : headersEnder
MetaHeadersFrame : headersOrContinuation
MetaHeadersFrame : streamEnder
MetaHeadersFrame : context.stringer
MetaHeadersFrame : net/http/internal/http2.headersEnder
MetaHeadersFrame : net/http/internal/http2.headersOrContinuation
MetaHeadersFrame : net/http/internal/http2.streamEnder
MetaHeadersFrame : runtime.stringer
OpenStreamOptions specifies extra options for WriteScheduler.OpenStream.
Deprecated: User-provided write schedulers are deprecated. PusherID is zero if the stream was initiated by the client. Otherwise,
PusherID names the stream that pushed the newly opened stream. priority is used to set the priority of 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 https://httpwg.org/specs/rfc7540.html#rfc.section.6.7Data[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.(*PingFrame) IsAck() bool( PingFrame) String() string(*PingFrame) checkValid()(*PingFrame) invalidate()( PingFrame) writeDebug(buf *bytes.Buffer)
*PingFrame : Frame
PingFrame : expvar.Var
PingFrame : fmt.Stringer
PingFrame : context.stringer
PingFrame : runtime.stringer
A PriorityFrame specifies the sender-advised priority of a stream.
See https://httpwg.org/specs/rfc7540.html#rfc.section.6.3FrameHeaderFrameHeader 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 "The incremental (i) parameter value is Boolean (see Section 3.3.6 of
[STRUCTURED-FIELDS]). It indicates if an HTTP response can be processed
incrementally, i.e., provide some meaningful output as chunks of the
response arrive."
We use uint8 (i.e. 0 is false, 1 is true) instead of bool so we can
avoid unnecessary type conversions and because either type takes 1 byte. "The urgency (u) parameter value is Integer (see Section 3.3.1 of
[STRUCTURED-FIELDS]), between 0 and 7 inclusive, in descending order of
priority. The default is 3." Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.( PriorityFrame) IsZero() bool( PriorityFrame) String() string(*PriorityFrame) checkValid()(*PriorityFrame) invalidate()( PriorityFrame) writeDebug(buf *bytes.Buffer)
*PriorityFrame : Frame
PriorityFrame : expvar.Var
PriorityFrame : fmt.Stringer
PriorityFrame : context.stringer
PriorityFrame : encoding/json/v2.isZeroer
PriorityFrame : runtime.stringer
PriorityParam are the stream prioritization 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." "The incremental (i) parameter value is Boolean (see Section 3.3.6 of
[STRUCTURED-FIELDS]). It indicates if an HTTP response can be processed
incrementally, i.e., provide some meaningful output as chunks of the
response arrive."
We use uint8 (i.e. 0 is false, 1 is true) instead of bool so we can
avoid unnecessary type conversions and because either type takes 1 byte. "The urgency (u) parameter value is Integer (see Section 3.3.1 of
[STRUCTURED-FIELDS]), between 0 and 7 inclusive, in descending order of
priority. The default is 3."( PriorityParam) IsZero() bool
PriorityParam : encoding/json/v2.isZeroer
func defaultRFC9218Priority(canUseDefault bool) PriorityParam
func parseRFC9218Priority(s string, canUseDefault bool) (p PriorityParam, ok bool)
func (*MetaHeadersFrame).rfc9218Priority(priorityAware bool) (p PriorityParam, priorityAwareAfter, hasIntermediary bool)
func (*Framer).WritePriority(streamID uint32, p PriorityParam) error
func WriteScheduler.AdjustStream(streamID uint32, priority PriorityParam)
PriorityUpdateFrame is a PRIORITY_UPDATE frame as described in
https://www.rfc-editor.org/rfc/rfc9218.html#name-the-priority_update-frame.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).PrioritizedStreamIDuint32Prioritystring // 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.( PriorityUpdateFrame) String() string(*PriorityUpdateFrame) checkValid()(*PriorityUpdateFrame) invalidate()( PriorityUpdateFrame) writeDebug(buf *bytes.Buffer)
*PriorityUpdateFrame : Frame
PriorityUpdateFrame : expvar.Var
PriorityUpdateFrame : fmt.Stringer
PriorityUpdateFrame : context.stringer
PriorityUpdateFrame : runtime.stringer
PriorityWriteSchedulerConfig configures a priorityWriteScheduler.
Deprecated: User-provided write schedulers are deprecated. 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 https://httpwg.org/specs/rfc7540.html#rfc.section.6.6FrameHeaderFrameHeader 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.(*PushPromiseFrame) HeaderBlockFragment() []byte(*PushPromiseFrame) HeadersEnded() bool( PushPromiseFrame) String() string(*PushPromiseFrame) checkValid()(*PushPromiseFrame) invalidate()( PushPromiseFrame) writeDebug(buf *bytes.Buffer)
*PushPromiseFrame : Frame
PushPromiseFrame : expvar.Var
PushPromiseFrame : fmt.Stringer
*PushPromiseFrame : headersEnder
*PushPromiseFrame : headersOrContinuation
PushPromiseFrame : context.stringer
*PushPromiseFrame : net/http/internal/http2.headersEnder
*PushPromiseFrame : net/http/internal/http2.headersOrContinuation
PushPromiseFrame : 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
A RSTStreamFrame allows for abnormal termination of a stream.
See https://httpwg.org/specs/rfc7540.html#rfc.section.6.4ErrCodeErrCodeFrameHeaderFrameHeader 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.( RSTStreamFrame) String() string(*RSTStreamFrame) checkValid()(*RSTStreamFrame) invalidate()( RSTStreamFrame) writeDebug(buf *bytes.Buffer)
*RSTStreamFrame : Frame
RSTStreamFrame : expvar.Var
RSTStreamFrame : fmt.Stringer
RSTStreamFrame : context.stringer
RSTStreamFrame : runtime.stringer
ServeConnOpts are options for the Server.ServeConn method.
Deprecated: ServeConnOpts is deprecated. BaseConfig optionally sets the base configuration
for values. If nil, defaults are used. Context is the base context to use.
If nil, context.Background is used. Handler specifies which handler to use for processing
requests. If nil, BaseConfig.Handler is used. If BaseConfig
or BaseConfig.Handler is nil, http.DefaultServeMux is used. SawClientPreface is set if the HTTP/2 connection preface
has already been read from the connection. Settings is the decoded contents of the HTTP2-Settings header
in an h2c upgrade request. UpgradeRequest is an initial request received on a connection
undergoing an h2c upgrade. The request body must have been
completely read from the connection before calling ServeConn,
and the 101 Switching Protocols response written.(*ServeConnOpts) baseConfig() *http.Server(*ServeConnOpts) context() context.Context(*ServeConnOpts) handler() http.Handler
func (*Server).ServeConn(c net.Conn, opts *ServeConnOpts)
func serverConnBaseContext(c net.Conn, opts *ServeConnOpts) (ctx context.Context, cancel func())
func (*Server).serveConn(c net.Conn, opts *ServeConnOpts, _ func(*serverConn))
Server is an HTTP/2 server.
Deprecated: Use [http.Server] instead. CountError, if non-nil, is called on HTTP/2 server errors.
It's intended to increment a metric for monitoring, such
as an expvar or Prometheus metric.
The errType consists of only ASCII word characters.
Deprecated: Use [http.Server.HTTP2] and
[http.HTTP2Config.CountError] instead. 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.
If zero or negative, there is no timeout.
Deprecated: Use [http.Server.IdleTimeout] instead. 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.
Deprecated: Use [http.Server.HTTP2] and
[http.HTTP2Config.MaxConcurrentStreams] instead. MaxDecoderHeaderTableSize optionally specifies the http2
SETTINGS_HEADER_TABLE_SIZE to send in the initial settings frame. It
informs the remote endpoint of the maximum size of the header compression
table used to decode header blocks, in octets. If zero, the default value
of 4096 is used.
Deprecated: Use [http.Server.HTTP2] and
[http.HTTP2Config.MaxDecoderHeaderTableSize] instead. MaxEncoderHeaderTableSize optionally specifies an upper limit for the
header compression table used for encoding request headers. Received
SETTINGS_HEADER_TABLE_SIZE settings are capped at this limit. If zero,
the default value of 4096 is used.
Deprecated: Use [http.Server.HTTP2] and
[http.HTTP2Config.MaxEncoderHeaderTableSize] instead. 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
Deprecated: This field has never had any effect. 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.
Deprecated: Use [http.Server.HTTP2] and
[http.HTTP2Config.MaxReadFrameSize] instead. 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.
Deprecated: Use [http.Server.HTTP2] and
[http.HTTP2Config.MaxReceiveBufferPerConnection] 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.
Deprecated: Use [http.Server.HTTP2] and
[http.HTTP2Config.MaxReceiveBufferPerStream] instead. NewWriteScheduler constructs a write scheduler for a connection.
If nil, a default scheduler is chosen.
Deprecated: User-provided write schedulers are deprecated. PermitProhibitedCipherSuites, if true, permits the use of
cipher suites prohibited by the HTTP/2 spec.
Deprecated: Use [http.Server.HTTP2] and
[http.HTTP2Config.PermitProhibitedCipherSuites] instead. PingTimeout is the timeout after which the connection will be closed
if a response to a ping is not received.
If zero, a default of 15 seconds is used.
Deprecated: Use [http.Server.HTTP2] and
[http.HTTP2Config.PingTimeout] instead. ReadIdleTimeout is the timeout after which a health check using a ping
frame will be carried out if no frame is received on the connection.
If zero, no health check is performed.
Deprecated: Use [http.Server.HTTP2] and
[http.HTTP2Config.SendPingTimeout] instead. WriteByteTimeout is the timeout after which a connection will be
closed if no data can be written to it. The timeout begins when data is
available to write, and is extended whenever any bytes are written.
If zero or negative, there is no timeout.
Deprecated: Use [http.Server.HTTP2] and
[http.HTTP2Config.WriteByteTimeout] instead. 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.
Deprecated: Use [http.Server.Serve] or [http.Server.ServeTLS] instead.(*Server) serveConn(c net.Conn, opts *ServeConnOpts, _ func(*serverConn))
func ConfigureServer(s *http.Server, conf *Server) error
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 https://httpwg.org/specs/rfc7540.html#SettingFormat Val is the value.( Setting) String() string Valid reports whether the setting is valid.
Setting : expvar.Var
Setting : fmt.Stringer
Setting : context.stringer
Setting : 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 https://httpwg.org/specs/rfc7540.html#SETTINGSFrameHeaderFrameHeader 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 Framep[]byte ForeachSetting runs fn for each setting.
It stops and returns the first error. HasDuplicates reports whether f contains any duplicate setting IDs. Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface.(*SettingsFrame) IsAck() bool(*SettingsFrame) 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().( SettingsFrame) String() string(*SettingsFrame) Value(id SettingID) (v uint32, ok bool)(*SettingsFrame) checkValid()(*SettingsFrame) invalidate()( SettingsFrame) writeDebug(buf *bytes.Buffer)
*SettingsFrame : Frame
SettingsFrame : expvar.Var
SettingsFrame : fmt.Stringer
SettingsFrame : context.stringer
SettingsFrame : runtime.stringer
Transport is an HTTP/2 Transport.
A Transport internally caches connections to servers. It is safe
for concurrent use by multiple goroutines.
Deprecated: Use [http.Transport] instead. AllowHTTP, if true, permits HTTP/2 requests using the insecure,
plain-text "http" scheme. Note that this does not enable h2c support.
Deprecated: Use [http.Transport.Protocols] instead. ConnPool optionally specifies an alternate connection pool to use.
If nil, the default is used.
Deprecated: To create a custom connection pool, implement
[http.RoundTripper]. Use [http.Transport.NewClientConn]
to create connections for the pool. CountError, if non-nil, is called on HTTP/2 transport errors.
It's intended to increment a metric for monitoring, such
as an expvar or Prometheus metric.
The errType consists of only ASCII word characters.
Deprecated: Use [http.Transport.HTTP2] and
[http.HTTP2Config.CountError] instead. DialTLS specifies an optional dial function for creating
TLS connections for requests.
If DialTLSContext and DialTLS is nil, tls.Dial is used.
Deprecated: Use [http.Transport.DialTLSContext] instead. DialTLSContext specifies an optional dial function with context for
creating TLS connections for requests.
If DialTLSContext and DialTLS is nil, tls.Dial is used.
If the returned net.Conn has a ConnectionState method like tls.Conn,
it will be used to set http.Response.TLS.
Deprecated: Use [http.Transport.DialTLSContext] instead. 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.
Deprecated: Use [http.Transport.DisableCompression] instead. IdleConnTimeout is the maximum amount of time an idle
(keep-alive) connection will remain idle before closing
itself.
Zero means no limit.
Deprecated: Use [http.Transport.IdleConnTimeout] instead. MaxDecoderHeaderTableSize optionally specifies the http2
SETTINGS_HEADER_TABLE_SIZE to send in the initial settings frame. It
informs the remote endpoint of the maximum size of the header compression
table used to decode header blocks, in octets. If zero, the default value
of 4096 is used.
Deprecated: Use [http.Transport.HTTP2] and
[http.HTTP2Config.MaxDecoderHeaderTableSize] instead. MaxEncoderHeaderTableSize optionally specifies an upper limit for the
header compression table used for encoding request headers. Received
SETTINGS_HEADER_TABLE_SIZE settings are capped at this limit. If zero,
the default value of 4096 is used.
Deprecated: Use [http.Transport.HTTP2] and
[http.HTTP2Config.MaxEncoderHeaderTableSize] instead. 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.
Deprecated: Use [http.Transport.MaxResponseHeaderBytes] instead. MaxReadFrameSize is the http2 SETTINGS_MAX_FRAME_SIZE to send in the
initial settings frame. It is the size in bytes of the largest frame
payload that the sender is willing to receive. If 0, no setting is
sent, and the value is provided by the peer, which should be 16384
according to the spec:
https://datatracker.ietf.org/doc/html/rfc7540#section-6.5.2.
Values are bounded in the range 16k to 16M.
Deprecated: Use [http.Transport.HTTP2] and
[http.HTTP2Config.MaxReadFrameSize] instead. PingTimeout is the timeout after which the connection will be closed
if a response to Ping is not received.
Defaults to 15s.
Deprecated: Use [http.Transport.HTTP2] and
[http.HTTP2Config.PingTimeout] instead. 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.
Deprecated: Use [http.Transport.HTTP2] and
[http.HTTP2Config.SendPingTimeout] instead. 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.
Deprecated: Use [http.Transport.HTTP2] and
[http.HTTP2Config.StrictMaxConcurrentRequests] instead. TLSClientConfig specifies the TLS configuration to use with
tls.Client. If nil, the default configuration is used.
Deprecated: Use [http.Transport.TLSClientConfig] instead. WriteByteTimeout is the timeout after which the connection will be
closed no data can be written to it. The timeout begins when data is
available to write, and is extended whenever any bytes are written.
Deprecated: Use [http.Transport.HTTP2] and
[http.HTTP2Config.WriteByteTimeout] instead. Internal state, differs between wrapped and non-wrapped implementations.transportInternal.dialMusync.MutextransportInternal.dialsmap[string]*transportDialStatetransportInternal.initOncesync.OncetransportInternal.lazyt1*http.Transport 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.
Deprecated: Use [http.Transport.CloseIdleConnections] instead. NewClientConn is deprecated.
Deprecated: Use [http.Transport.NewClientConn] instead. Deprecated: Use [http.Transport.RoundTrip] instead. RoundTripOpt is like RoundTrip, but takes options.
Deprecated: Use [http.Transport.RoundTrip] instead.(*Transport) closeIdleConnections()(*Transport) configure(t1 *http.Transport) dialForRoundTrip is called (indirectly) by net/http when dialing a new connection
for a request call which originated as an http2.Transport.RoundTrip call.
It uses the http2.Transport's Dial hooks and coalesces dials.(*Transport) dialTLS(ctx context.Context, network, addr string, tlsCfg *tls.Config) (net.Conn, error) dialTLSWithContext uses tls.Dialer, added in Go 1.15, to open a TLS
connection.(*Transport) init() *http.Transport(*Transport) logf(format string, args ...interface{})(*Transport) newUserClientConn(c net.Conn) (*ClientConn, error)(*Transport) roundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Response, error)(*Transport) roundTripViaPool(req *http.Request, opt RoundTripOpt, pool ClientConnPool) (*http.Response, error)(*Transport) vlogf(format string, args ...interface{})
*Transport : net/http.RoundTripper
*Transport : net/http.closeIdleConnectionser
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 Framep[]byte Header returns h. It exists so FrameHeaders can be embedded in other
specific frame types and implement the Frame interface. Payload returns the frame's payload (after the header). It is not
valid to call this method after a subsequent call to
Framer.ReadFrame, nor is it valid to retain the returned slice.
The memory is owned by the Framer and is invalidated when the next
frame is read.( UnknownFrame) String() string(*UnknownFrame) checkValid()(*UnknownFrame) invalidate()( UnknownFrame) writeDebug(buf *bytes.Buffer)
*UnknownFrame : Frame
UnknownFrame : expvar.Var
UnknownFrame : fmt.Stringer
UnknownFrame : context.stringer
UnknownFrame : runtime.stringer
A WindowUpdateFrame is used to implement flow control.
See https://httpwg.org/specs/rfc7540.html#rfc.section.6.9FrameHeaderFrameHeader 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.( WindowUpdateFrame) String() string(*WindowUpdateFrame) checkValid()(*WindowUpdateFrame) invalidate()( WindowUpdateFrame) writeDebug(buf *bytes.Buffer)
*WindowUpdateFrame : Frame
WindowUpdateFrame : expvar.Var
WindowUpdateFrame : fmt.Stringer
WindowUpdateFrame : context.stringer
WindowUpdateFrame : runtime.stringer
WriteScheduler is the interface implemented by HTTP/2 write schedulers.
Methods are never called concurrently.
Deprecated: User-provided write schedulers are deprecated. AdjustStream adjusts the priority of the given stream. This may be called
on a stream that has not yet been opened or has been closed. Note that
RFC 7540 allows PRIORITY frames to be sent on streams in any state. See:
https://tools.ietf.org/html/rfc7540#section-5.1 CloseStream closes a stream in the write scheduler. Any frames queued on
this stream should be discarded. It is illegal to call this on a stream
that is not open -- the call may panic. OpenStream opens a new stream in the write scheduler.
It is illegal to call this with streamID=0 or with a streamID that is
already open -- the call may panic. Pop dequeues the next frame to write. Returns false if no frames can
be written. Frames with a given wr.StreamID() are Pop'd in the same
order they are Push'd, except RST_STREAM frames. No frames should be
discarded except by CloseStream. Push queues a frame in the scheduler. In most cases, this will not be
called with wr.StreamID()!=0 unless that stream is currently open. The one
exception is RST_STREAM frames, which may be sent on idle or closed streams.unsupportedWriteScheduler
func NewPriorityWriteScheduler(cfg *PriorityWriteSchedulerConfig) WriteScheduler
func NewRandomWriteScheduler() WriteScheduler
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, WriteByteTimeout // immutable(*bufferedWriter) Available() int(*bufferedWriter) Flush() error(*bufferedWriter) Write(p []byte) (n int, err error)
*bufferedWriter : internal/bisect.Writer
*bufferedWriter : io.Writer
*bufferedWriter : crypto/tls.transcriptHash
func newBufferedWriter(conn net.Conn, timeout time.Duration) *bufferedWriter
// non-nil when data is buffered // immutable, WriteByteTimeout // immutable(*bufferedWriterTimeoutWriter) Write(p []byte) (n int, err error)
*bufferedWriterTimeoutWriter : internal/bisect.Writer
*bufferedWriterTimeoutWriter : io.Writer
*bufferedWriterTimeoutWriter : crypto/tls.transcriptHash
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( connError) Error() string
connError : error
connOutflow is connection-level outbound flow control. // set when a flow control error is encountered // SETTINGS_INITIAL_WINDOW_SIZE, changes with settings updates // connection-level flow control window(*connOutflow) add(n int32) bool(*connOutflow) changeInitialWindowSize(size int64) bool(*connOutflow) init()
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.(*dataBuffer) bytesFromFirstChunk() []byte(*dataBuffer) lastChunkOrAlloc(want int64) []byte
*dataBuffer : internal/bisect.Writer
*dataBuffer : io.Reader
*dataBuffer : io.ReadWriter
*dataBuffer : io.Writer
*dataBuffer : pipeBuffer
*dataBuffer : crypto/tls.transcriptHash
*dataBuffer : net/http/internal/http2.pipeBuffer
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
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."( goAwayFlowError) Error() string
goAwayFlowError : error
http2TransportContextKey marks a RoundTrip as needing its dial handled by the http2.Transport.
We set this for http2.RoundTrip calls, where the historical behavior is to use the
http2.Transport's dialer.
incomparable is a zero-width, non-comparable type. Adding it to a struct
makes that struct also non-comparable, and generally doesn't add
any size (as long as it's first).
inflow accounts for an inbound flow control window.
It tracks both the latest window sent to the peer (used for enforcement)
and the accumulated unsent window.availint32unsentint32 add adds n bytes to the window, with a maximum window size of max,
indicating that the peer can now send us more data.
For example, the user read from a {Request,Response} body and consumed
some of the buffered data, so the peer can now send more.
It returns the number of bytes to send in a WINDOW_UPDATE frame to the peer.
Window updates are accumulated and sent when the unsent capacity
is at least inflowMinRefresh or will at least double the peer's available window. init sets the initial window. take attempts to take n bytes from the peer's flow control window.
It reports whether the window has available capacity.
func takeInflows(f1, f2 *inflow, n uint32) bool
netConnContextKey passes a net.Conn to http.Transport.NewClientConn.
See http2.Transport.NewClientConn.
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.( noCachedConnError) Error() string( noCachedConnError) IsHTTP2NoCachedConnError()
noCachedConnError : error
outflow is the stream-level outbound flow control window's size. conn points to the shared connection-level outflow that is
shared by all streams on that conn. delta is the difference between the stream's flow control window and
the connection's initial window size (conn.initial).
Another view is that delta is the number of flow control bytes provided to this
stream in WINDOW_UPDATE frames, less the number of bytes sent on the stream. add adds n bytes (positive or negative) to the flow control window.
It returns false if the sum would exceed 2^31-1.(*outflow) available() (int32, bool)(*outflow) take(n int32)
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.(*pipe) 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.(*pipe) closeWithError(dst *error, err error, fn func()) closeWithErrorAndCode is like CloseWithError but also sets some code to run
in the caller's goroutine before returning the error. setBuffer initializes the pipe buffer.
It has no effect if the pipe is already closed.
*pipe : internal/bisect.Writer
*pipe : io.Reader
*pipe : io.ReadWriter
*pipe : io.Writer
*pipe : pipeBuffer
*pipe : crypto/tls.transcriptHash
*pipe : net/http/internal/http2.pipeBuffer
// 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.(*sorter) Len() int(*sorter) Less(i, j int) bool(*sorter) SortStrings(ss []string)(*sorter) Swap(i, j int)
*sorter : sort.Interface
transportConfig is passed to net/http.Transport.RegisterProtocol("http/2", config).
It provides the net/http.Transport with access to the configuration in the
x/net/http2.Transport.t*Transport ConnFromContext lets the http.Transport fetch a net.Conn out of a context
passed to NewClientConn. See http2.Transport.NewClientConn. DialFromContext dials a new connection using the http2.Transport's DialTLS/DialTLSContext.( transportConfig) DisableCompression() bool ExternalRoundTrip reports whether the Transport wants to take control of the RoundTrip call.
If the user hasn't configured a custom connection pool, we leave the RoundTrip up to net/http.( transportConfig) HTTP2Config() http.HTTP2Config( transportConfig) IdleConnTimeout() time.Duration( transportConfig) MaxHeaderListSize() int64 Registered is called by net/http.Transport.RegisterProtocol,
to let us know that it understands the registration mechanism we're using. RoundTrip is used when the http.Transport is passing control of the full
RoundTrip to us--connection pooling, retries, etc.
This is only used when the http2.Transport has a user-provided ConnPool.
Any other time, net/http handles everything.
transportConfig : net/http.RoundTripper
transportConfig : net/http.http2Configer
transportConfig : net/http.http2ExternalTransportConfig
// dial result, set before dialc is closed // close when dial returns // closed when RoundTrip initiating the dial returns
transportRoundTripState is the state of the dial for an http2.Transport.RoundTrip. // closed when GotConn hook is calledmusync.Mutex // set when RoundTrip returns // closed when RoundTrip returns gotConn is called when RoundTrip gets a connection.
This may happen multiple times per RoundTrip, if a request is retried. roundTripDone is called when RoundTrip returns. startDial is called when a dial starts.
It returns done=true if the RoundTrip has already returned,
in which case we should skip dialing.
func (*Transport).dialForRoundTrip(ctx context.Context, dial *transportRoundTripState, network, address string) (net.Conn, error)
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.( writeContext) CloseConn() error( writeContext) Flush() error( writeContext) Framer() *Framer HeaderEncoder returns an HPACK encoder that writes to the
returned buffer.
func splitHeaderBlock(ctx writeContext, headerBlock []byte, fn func(ctx writeContext, frag []byte, firstFrag, lastFrag bool) error) error
func StreamError.writeFrame(ctx writeContext) error
writePushPromise is a request to write a PUSH_PROMISE and 0+ CONTINUATION frames. Creates an ID for a pushed stream. This runs on serveG just before
the frame is written. The returned ID is copied to promisedID.hhttp.Header // for :methodpromisedIDuint32 // pusher stream // for :scheme, :authority, :path(*writePushPromise) staysWithinBuffer(max int) bool(*writePushPromise) writeFrame(ctx writeContext) error(*writePushPromise) writeHeaderBlock(ctx writeContext, frag []byte, firstFrag, lastFrag bool) error
*writePushPromise : writeFramer
Package-Level Functions (total 67, 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.
Deprecated: Set [http.Server.Protocols] instead.
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.
Deprecated: Set [http.Transport.Protocols] instead.
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.
Deprecated: Set [http.Transport.Protocols] instead.
NewFramer returns a Framer that writes frames to w and reads them from r.
NewPriorityWriteScheduler is deprecated.
Deprecated: User-provided write schedulers are deprecated.
NewRandomWriteScheduler is deprecated.
Deprecated: User-provided write schedulers are deprecated.
ReadFrameHeader reads 9 bytes from r and returns a FrameHeader.
Most users should use Framer.ReadFrame instead.
asciiEqualFold is strings.EqualFold, ASCII only. It reports whether s and t
are equal, ASCII-case-insensitively.
asciiToLower returns the lowercase version of s if s is ASCII and printable,
and whether or not it was.
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.
bodyAllowedForStatus reports whether a given response status code
permits a body. See RFC 7230, section 3.3.
Return the first number n such that n*base >= 1<<64.
defaultRFC9218Priority determines what priority we should use as the default
value.
According to RFC 9218, by default, streams should be given an urgency of 3
and should be non-incremental. However, making streams non-incremental by
default would be a huge change to our historical behavior where we would
round-robin writes across streams. When streams are non-incremental, we
would process streams of the same urgency one-by-one to completion instead.
To avoid such a sudden change which might break some HTTP/2 users, this
function allows the caller to specify whether they can actually use the
default value as specified in RFC 9218. If not, this function will return a
priority value where streams are incremental by default instead: effectively
a round-robin between stream of the same urgency.
As an example, a server might not be able to use the RFC 9218 default value
when it's not sure that the client it is serving is aware of RFC 9218.
isASCIIPrint returns whether s is ASCII and printable according to
https://tools.ietf.org/html/rfc20#section-4.2.
isBadCipher reports whether the cipher is blacklisted by the HTTP/2 spec.
References:
https://tools.ietf.org/html/rfc7540#appendix-A
Reject cipher suites from Appendix A.
"This list includes those cipher suites that do not
offer an ephemeral key exchange and those that are
based on the TLS null, stream or block cipher type"
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.
splitHeaderBlock splits headerBlock into fragments so that each fragment fits
in a single frame, then calls fn for each fragment. firstFrag/lastFrag are true
for the first/last fragment, respectively.
takeInflows attempts to take n bytes from two inflows,
typically connection-level and stream-level flows.
It reports whether both windows have available capacity.
terminalReadFrameError reports whether err is an unrecoverable
error from ReadFrame and no other frames should be read.
traceGotConn is (when http2legacy is not enabled) only used for tracing
connections acquired while using a user-provided ClientConnPool.
unencryptedNetConnFromTLSConn retrieves a net.Conn wrapped in a *tls.Conn.
TLSNextProto functions accept a *tls.Conn.
When passing an unencrypted HTTP/2 connection to a TLSNextProto function,
we pass a *tls.Conn with an underlying net.Conn containing the unencrypted connection.
To be extra careful about mistakes (accidentally dropping TLS encryption in a place
where we want it), the tls.Conn contains a net.Conn with an UnencryptedNetConn method
that returns the actual connection we want to use.
validWireHeaderFieldName reports whether v is a valid header field
name (key). See httpguts.ValidHeaderFieldName 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).
writeWithByteTimeout writes to conn.
If more than timeout passes without any bytes being written to the connection,
the write fails.
Package-Level Variables (total 41, in which 6 are exported)
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))
Setting DebugGoroutines to false during a test to disable goroutine debugging
results in race detector complaints when a test leaves goroutines running before
returning. Tests shouldn't do this, of course, but when they do it generally shows
up as infrequent, hard-to-debug flakes. (See #66519.)
Disable goroutine debugging during individual tests with an atomic bool.
(Note that it's safe to enable/disable debugging mid-test, so the actual race condition
here is harmless.)
Enabling extended CONNECT by causes browsers to attempt to use
WebSockets-over-HTTP/2. This results in problems when the server's websocket
package doesn't support extended CONNECT.
Disable extended CONNECT by default for now.
Issue #71128.
errFromPeer is a sentinel error value for StreamError.Cause to
indicate that the StreamError was sent from the peer over the wire
and wasn't locally generated in the Transport.
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
Deprecated: Use [http.TrailerPrefix] instead.
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.
The pages are generated with Goldsv0.8.4. (GOOS=linux GOARCH=amd64)