http3

package
v1.0.38 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 16, 2026 License: MIT, MIT Imports: 34 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

HTTP/3

Documentation PkgGoDev

This package implements HTTP/3 (RFC 9114), including QPACK (RFC 9204) and HTTP Datagrams (RFC 9297). It aims to provide feature parity with the standard library's HTTP/1.1 and HTTP/2 implementation.

Detailed documentation can be found on quic-go.net.

This fork tracks quic-go v0.65.0 and uses github.com/enetx/http. It preserves configurable request header order and ordered HTTP/3 settings. See UPSTREAM.md for the fork audit, retained changes and Surf API usage.

Run the upstream and fork regression suites with go test -race ./... and go vet ./....

Documentation

Index

Constants

View Source
const (
	// MethodGet0RTT allows a GET request to be sent using 0-RTT.
	// Note that 0-RTT doesn't provide replay protection and should only be used for idempotent requests.
	MethodGet0RTT = "GET_0RTT"
	// MethodHead0RTT allows a HEAD request to be sent using 0-RTT.
	// Note that 0-RTT doesn't provide replay protection and should only be used for idempotent requests.
	MethodHead0RTT = "HEAD_0RTT"
)
View Source
const (
	QPACKHuffmanDefault = dynamic.HuffmanDefault
	QPACKHuffmanAuto    = dynamic.HuffmanAuto
	QPACKHuffmanAlways  = dynamic.HuffmanAlways
	QPACKHuffmanNever   = dynamic.HuffmanNever
	QPACKIndexAll       = dynamic.IndexAll
	QPACKIndexNewNames  = dynamic.IndexNewNames
	QPACKIndexNone      = dynamic.IndexNone
)
View Source
const CapsuleProtocolHeader = "Capsule-Protocol"

CapsuleProtocolHeader is the header value used to advertise support for the capsule protocol

View Source
const NextProtoH3 = "h3"

NextProtoH3 is the ALPN protocol negotiated during the TLS handshake, for QUIC v1 and v2.

Variables

View Source
var (
	// ErrNoCachedConn is returned by [Transport.RoundTripOpt] when [RoundTripOpt.OnlyCachedConn]
	// is true and no cached connection is available.
	ErrNoCachedConn = errors.New("http3: no cached connection was available")
	// ErrTransportClosed is returned by [Transport.RoundTrip] and [Transport.RoundTripOpt]
	// after the transport is closed.
	ErrTransportClosed = errors.New("http3: transport is closed")
)
View Source
var ErrNoAltSvcPort = errors.New("no port can be announced, specify it explicitly using Server.Port or Server.Addr")

ErrNoAltSvcPort is returned by Server.SetQUICHeaders when no port was found for Alt-Svc to announce. This can happen if listening on a net.PacketConn without a port (UNIX socket, for example) and no port is specified in Server.Port or Server.Addr.

View Source
var ErrRequestCompleted = errors.New("http3: request has completed")

ErrRequestCompleted means the request can no longer be reprioritized.

View Source
var RemoteAddrContextKey = &contextKey{"remote-addr"}

RemoteAddrContextKey is a context key. It can be used in HTTP handlers with context.Context.Value to access the remote address of the connection. The associated value will be of type net.Addr.

Use this value instead of http.Request.RemoteAddr if you require access to the remote address of the connection rather than its string representation.

View Source
var ServerContextKey = &contextKey{"http3-server"}

ServerContextKey is a context key. It can be used in HTTP handlers with context.Context.Value to access the server that started the handler. The associated value will be of type *Server.

Functions

func ConfigureTLSConfig

func ConfigureTLSConfig(tlsConf *tls.Config) *tls.Config

ConfigureTLSConfig creates a new tls.Config which can be used to create a quic.Listener meant for serving HTTP/3.

func IsEarlyRequest added in v1.0.37

func IsEarlyRequest(req *http.Request) bool

IsEarlyRequest reports whether this request's header preparation skipped authenticated connection initialization through the early request path. It is intended for Transport.PrepareHeaders and the resulting Response.Request. The decision is frozen before preparation, regardless of concurrent handshake completion; it does not prove that any packet used 0-RTT encryption. Magic early methods with an already-complete handshake initialize normally and report false, including warm requests after an accepted 0-RTT connection. Nil and requests outside this preparation path return false.

func ListenAndServeQUIC

func ListenAndServeQUIC(addr, certFile, keyFile string, handler http.Handler) error

ListenAndServeQUIC listens on the UDP network address addr and calls the handler for HTTP/3 requests on incoming connections. http.DefaultServeMux is used when handler is nil.

func ListenAndServeTLS

func ListenAndServeTLS(addr, certFile, keyFile string, handler http.Handler) error

ListenAndServeTLS listens on the given network address for both TLS/TCP and QUIC connections in parallel. It returns if one of the two returns an error. http.DefaultServeMux is used when handler is nil. The correct Alt-Svc headers for QUIC are set.

func NotifyConnectionStarted added in v1.0.29

func NotifyConnectionStarted(ctx context.Context)

NotifyConnectionStarted lets a custom Transport.Dial report that DNS and socket preparation are complete and a QUIC handshake is starting. Call before entering the QUIC dial. Repeated calls are safe; contexts without a transport observer are unchanged. Notifications belong to the actual shared pool dial, so all PreconnectWithOptions waiters observe the same connection attempt.

func WithPriorityUpdateHandler added in v1.0.5

func WithPriorityUpdateHandler(ctx context.Context, handler func(*PriorityUpdater)) context.Context

WithPriorityUpdateHandler calls handler after successful request HEADERS on each HTTP/3 attempt. The handler must return promptly; it may retain the updater and use it until the response body is closed, read to EOF, or canceled. It does not change the Priority header or invent resource loading scenarios.

func WithStreamPriority

func WithStreamPriority(ctx context.Context, priority StreamPriority) context.Context

WithStreamPriority overrides local QUIC scheduling for one HTTP/3 request. Pass the returned context to Request.WithContext. This takes precedence over Transport.StreamPriority and does not change HTTP headers or control frames.

func WriteCapsule

func WriteCapsule(w quicvarint.Writer, ct CapsuleType, value []byte) error

WriteCapsule writes a capsule

Types

type CapsuleParser

type CapsuleParser struct {
	// contains filtered or unexported fields
}

CapsuleParser parses a sequence of capsules. A capsule's contents must be fully consumed or discarded before calling CapsuleParser.Next again.

func NewCapsuleParser

func NewCapsuleParser(r io.Reader) *CapsuleParser

NewCapsuleParser creates a parser that reads capsules from r.

func (*CapsuleParser) Next

Next returns the type and contents of the next capsule. The previous capsule's contents must be fully consumed or discarded before calling this method again.

type CapsuleReader

type CapsuleReader struct {
	// contains filtered or unexported fields
}

CapsuleReader reads the contents of a capsule. It becomes invalid after CapsuleParser.Next successfully advances to the next capsule.

func (CapsuleReader) Discard

func (r CapsuleReader) Discard() error

Discard consumes the remaining capsule contents.

func (CapsuleReader) Read

func (r CapsuleReader) Read(b []byte) (int, error)

Read reads from the capsule contents.

func (CapsuleReader) ReadByte

func (r CapsuleReader) ReadByte() (byte, error)

ReadByte reads one byte from the capsule contents.

func (CapsuleReader) Remaining

func (r CapsuleReader) Remaining() int64

Remaining returns the number of bytes remaining in the capsule.

type CapsuleType

type CapsuleType uint64

CapsuleType is the type of the capsule

type ClientConn

type ClientConn struct {
	// contains filtered or unexported fields
}

ClientConn is an HTTP/3 client doing requests to a single remote server.

func (*ClientConn) CloseWithError

func (c *ClientConn) CloseWithError(code quic.ApplicationErrorCode, msg string) error

CloseWithError closes the connection with the given error code and message. It is invalid to call this function after the connection was closed.

func (*ClientConn) Context

func (c *ClientConn) Context() context.Context

Context returns a context that is cancelled when the connection is closed.

func (*ClientConn) HandleBidirectionalStream

func (c *ClientConn) HandleBidirectionalStream(str *quic.Stream)

HandleBidirectionalStream handles an incoming bidirectional stream.

func (*ClientConn) LocalAddr

func (c *ClientConn) LocalAddr() net.Addr

LocalAddr returns the local address of the underlying QUIC connection.

func (*ClientConn) OpenRequestStream

func (c *ClientConn) OpenRequestStream(ctx context.Context) (*RequestStream, error)

OpenRequestStream opens a new request stream on the HTTP/3 connection.

func (*ClientConn) ReceivedSettings

func (c *ClientConn) ReceivedSettings() <-chan struct{}

ReceivedSettings returns a channel that is closed once the server's HTTP/3 settings were received. The settings can be obtained from ClientConn.Settings after the channel is closed.

func (*ClientConn) RemoteAddr

func (c *ClientConn) RemoteAddr() net.Addr

RemoteAddr returns the remote address of the underlying QUIC connection.

func (*ClientConn) RoundTrip

func (c *ClientConn) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip executes a request and returns a response

func (*ClientConn) Settings

func (c *ClientConn) Settings() *Settings

Settings returns the HTTP/3 settings for this connection. It is only valid to call this method after the channel returned by ClientConn.ReceivedSettings is closed.

type ConnectionReuseInfo added in v1.0.25

type ConnectionReuseInfo struct {
	// Authority is the requested canonical host:port.
	Authority string
	// OriginalAuthority is the host:port used to establish this pooled connection.
	OriginalAuthority string
	// Conn is the transport-owned candidate connection.
	Conn *quic.Conn
	// AllowNetwork is false during the first pass over all candidates. Policies
	// should defer DNS/network lookups until the second pass, where it is true.
	// This lets explicit existing authorizations win before route resolution.
	AllowNetwork bool
}

ConnectionReuseInfo describes a candidate owned by this transport's pool. Authority and OriginalAuthority are canonical host:port pairs. Conn remains transport-owned and must not be closed or have its accept loops taken over.

type ControlFrame added in v1.0.25

type ControlFrame struct {
	// Type is the extension's HTTP/3 frame identifier.
	Type uint64
	// Length is the declared payload length, excluding the frame header.
	Length uint64
	// Payload is bounded to Length bytes. A truncated peer stream can still
	// return EOF early; handlers must enforce framing before publishing state.
	Payload io.Reader
}

ControlFrame exposes an otherwise unhandled peer control-stream extension. It is valid only while WireConfig.OnControlFrame is running.

type ErrCode

type ErrCode quic.ApplicationErrorCode
const (
	ErrCodeNoError                  ErrCode = 0x100
	ErrCodeGeneralProtocolError     ErrCode = 0x101
	ErrCodeInternalError            ErrCode = 0x102
	ErrCodeStreamCreationError      ErrCode = 0x103
	ErrCodeClosedCriticalStream     ErrCode = 0x104
	ErrCodeFrameUnexpected          ErrCode = 0x105
	ErrCodeFrameError               ErrCode = 0x106
	ErrCodeExcessiveLoad            ErrCode = 0x107
	ErrCodeIDError                  ErrCode = 0x108
	ErrCodeSettingsError            ErrCode = 0x109
	ErrCodeMissingSettings          ErrCode = 0x10a
	ErrCodeRequestRejected          ErrCode = 0x10b
	ErrCodeRequestCanceled          ErrCode = 0x10c
	ErrCodeRequestIncomplete        ErrCode = 0x10d
	ErrCodeMessageError             ErrCode = 0x10e
	ErrCodeConnectError             ErrCode = 0x10f
	ErrCodeVersionFallback          ErrCode = 0x110
	ErrCodeDatagramError            ErrCode = 0x33
	ErrCodeQPACKDecompressionFailed ErrCode = 0x200
	ErrCodeQPACKEncoderStreamError  ErrCode = 0x201
	ErrCodeQPACKDecoderStreamError  ErrCode = 0x202
)

func (ErrCode) String

func (e ErrCode) String() string

type Error

type Error struct {
	Remote       bool
	ErrorCode    ErrCode
	ErrorMessage string
	// contains filtered or unexported fields
}

Error is returned, possibly wrapped, by Stream and RequestStream operations, ClientConn.OpenRequestStream, Transport.RoundTrip, Transport.RoundTripOpt, and ClientConn.RoundTrip for HTTP clients, and from request-body reads and response writes inside HTTP handlers for HTTP servers, when an HTTP/3 error occurs. See section 8 of RFC 9114.

An Error returned by this package wraps a quic.StreamError for stream cancellations or a quic.ApplicationError for connection closure. Other QUIC errors are returned without conversion to Error.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Is

func (e *Error) Is(target error) bool

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying error.

type FrameType

type FrameType uint64

FrameType is the frame type of a HTTP/3 frame

type GreaseFrame added in v1.0.2

type GreaseFrame struct {
	Type    uint64
	Payload []byte
}

GreaseFrame is an RFC 9114 reserved frame (type 0x1f*N+0x21). Browser-specific types, payloads and random distributions belong to the caller.

type HTTPStreamer

type HTTPStreamer interface {
	HTTPStream() (*Stream, error)
}

HTTPStreamer allows an HTTP handler to take over an HTTP/3 stream. It is implemented by the http.ResponseWriter passed to HTTP/3 handlers. When a stream is taken over, it's the caller's responsibility to close the stream.

If WriteHeader was called before HTTPStream, the response header is sent. Otherwise, no response is sent. HTTPStream fails if any response body was written. If sending the header fails, the stream is not taken over, and HTTPStream can be called again. Calling WriteHeader after HTTPStream panics, and Write returns http.ErrHijacked.

type PreconnectOptions added in v1.0.29

type PreconnectOptions struct {
	// Early returns at 0-RTT encryption readiness when available. False waits
	// for the authenticated TLS handshake, independently of early setup frames.
	Early bool
	// OnConnectionStarted runs once in this caller after the actual pooled
	// connection starts, including when joining a dial that has already started.
	// It must return promptly. The default dialer reports the event after DNS;
	// custom Dial implementations must call NotifyConnectionStarted themselves.
	OnConnectionStarted func()
}

PreconnectOptions controls connection readiness without sending a request.

type PriorityUpdater added in v1.0.5

type PriorityUpdater struct {
	// contains filtered or unexported fields
}

PriorityUpdater changes the peer's response priority for one request. It is concurrency safe and independent of the local QUIC upload scheduler. Repeated values are suppressed. A successful Update queues a control frame; delivery still depends on the connection and peer.

func (*PriorityUpdater) Update added in v1.0.5

func (p *PriorityUpdater) Update(urgency int8, incremental bool) error

Update queues RFC 9218 PRIORITY_UPDATE. Urgency must be between 0 and 7. Updating to (3, false) resets the peer to the default priority.

type QPACKCapacityTiming added in v1.0.1

type QPACKCapacityTiming uint8

QPACKCapacityTiming selects when to queue an encoder capacity instruction.

const (
	QPACKCapacityOnSettings QPACKCapacityTiming = iota
	QPACKCapacityBeforeHeaders
)

type QPACKConfig added in v1.0.1

type QPACKConfig struct {
	DynamicTable bool
	Huffman      QPACKHuffmanMode
	Indexing     QPACKIndexingMode
	// IndexingPolicy controls insertion of new entries; existing references remain
	// usable. Called under encoder locks; must not reenter the transport.
	IndexingPolicy func(name, value string) bool
	// ResumptionErrorCode optionally selects the close code when accepted 0-RTT
	// changes a remembered nonzero maximum table capacity. Nil or a zero result
	// selects RFC 9204's QPACK_DECODER_STREAM_ERROR. Called during SETTINGS parsing;
	// it may run concurrently and must not perform I/O. Values outside the QUIC
	// range become H3_INTERNAL_ERROR.
	ResumptionErrorCode func(previous, current uint64) ErrCode
	// DrainingFraction reserves this fraction of table space for eviction.
	// Draining exact entries can be duplicated while their old references drain.
	DrainingFraction float64
	// PostBaseReferences fixes Base before this section's insertions. Otherwise
	// Base equals Required Insert Count and all references are Base-relative.
	PostBaseReferences bool
	// LiteralInsertNames disables name references in Insert instructions.
	LiteralInsertNames bool
	// StopOnInsertionFailure stops new insertion attempts for the rest of a
	// section after the first entry cannot fit. Existing references remain usable.
	StopOnInsertionFailure bool
	// MaxTrackedSections bounds outstanding dynamic section bookkeeping. Zero
	// selects 4096; at the limit new sections use static encoding without waiting.
	MaxTrackedSections uint64
	// SplitCookies emits one field per nonempty cookie-pair, preserving order.
	SplitCookies bool
	// NeverIndex emits these lowercase field names as literals with N=1.
	// These fields bypass the dynamic table entirely.
	NeverIndex []string
	// StreamOrder reserves these streams after the control stream, in order,
	// while stream credit permits. Omitted streams are opened on demand.
	StreamOrder []QPACKStreamType
	// EagerStreamTypes queues the type byte at initialization for listed streams.
	// Otherwise the type is sent with the first instruction on that stream.
	EagerStreamTypes bool
	// EncoderTableCapacity bounds the capacity announced to the peer. Zero
	// disables dynamic insertion. The actual value is capped by peer SETTINGS;
	// EncoderZeroCapacity separately controls explicit zero announcements.
	EncoderTableCapacity uint64
	// EncoderZeroCapacity sends a capacity-zero instruction even when the peer
	// offers no table, initializing an otherwise lazy encoder stream.
	EncoderZeroCapacity bool
	// EncoderCapacityRequiresSetting suppresses capacity announcements when
	// the peer omitted SETTINGS_QPACK_MAX_TABLE_CAPACITY. An explicit zero
	// remains distinct and is governed by EncoderZeroCapacity.
	EncoderCapacityRequiresSetting bool
	// EncoderCapacityTiming selects immediate queuing after SETTINGS or queuing
	// while encoding the next HEADERS block. Network delivery remains asynchronous.
	EncoderCapacityTiming QPACKCapacityTiming
}

QPACKConfig controls client streams, capacity announcements and request fields. Nil preserves native behavior. Dynamic request compression is explicitly opt-in.

func (*QPACKConfig) Clone added in v1.0.1

func (q *QPACKConfig) Clone() *QPACKConfig

Clone snapshots the mutable stream order and field names.

func (*QPACKConfig) Validate added in v1.0.1

func (q *QPACKConfig) Validate() error

Validate checks stream types, duplicate reservations and capacity bounds.

type QPACKHuffmanMode added in v1.0.5

type QPACKHuffmanMode = dynamic.HuffmanMode

type QPACKIndexingMode added in v1.0.5

type QPACKIndexingMode = dynamic.IndexingMode

type QPACKStreamType added in v1.0.1

type QPACKStreamType uint64

QPACKStreamType identifies a client QPACK unidirectional stream.

const (
	QPACKEncoderStream QPACKStreamType = 2
	QPACKDecoderStream QPACKStreamType = 3
)

type QUICListener

type QUICListener interface {
	Accept(context.Context) (*quic.Conn, error)
	Addr() net.Addr
	io.Closer
}

A QUICListener listens for incoming QUIC connections.

type RawClientConn

type RawClientConn struct {
	*ClientConn
}

RawClientConn is a low-level HTTP/3 client connection. It allows the application to take control of the stream accept loops, giving the application the ability to handle streams originating from the server.

func (*RawClientConn) HandleUnidirectionalStream

func (c *RawClientConn) HandleUnidirectionalStream(str *quic.ReceiveStream)

HandleUnidirectionalStream handles an incoming unidirectional stream.

type RawServerConn

type RawServerConn struct {
	// contains filtered or unexported fields
}

RawServerConn is an HTTP/3 server connection. It can be used for advanced use cases where the application wants to manage the QUIC connection lifecycle.

func (*RawServerConn) CloseWithError

func (c *RawServerConn) CloseWithError(code quic.ApplicationErrorCode, msg string) error

CloseWithError closes the connection with the given error code and message.

func (*RawServerConn) HandleRequestStream

func (c *RawServerConn) HandleRequestStream(str *quic.Stream)

HandleRequestStream handles an HTTP/3 request on a bidirectional request stream. The stream can either be obtained by calling quic.Conn.AcceptStream on the underlying QUIC connection, or (internally) by using the server's stream accept loop.

func (*RawServerConn) HandleUnidirectionalStream

func (c *RawServerConn) HandleUnidirectionalStream(str *quic.ReceiveStream)

HandleUnidirectionalStream handles an incoming unidirectional stream.

type RequestBodyReadInfo added in v1.0.6

type RequestBodyReadInfo struct {
	Request      *http.Request
	HeaderFields []qpack.HeaderField
	BufferSize   int
}

RequestBodyReadInfo describes the validated outgoing request before QPACK state changes. HeaderFields contains the actual wire fields, including implicit headers. It is a private copy and may be retained by the callback. Request must not be mutated. BufferSize is the effective body read buffer.

type RequestPreparationError added in v1.0.2

type RequestPreparationError struct {
	// contains filtered or unexported fields
}

RequestPreparationError reports a local peer-settings, header preparation, frame factory or control queue failure before request bytes are written. It unwraps the original cause, but should not trigger protocol fallback or a retry on a different connection.

func (*RequestPreparationError) Error added in v1.0.2

func (e *RequestPreparationError) Error() string

func (*RequestPreparationError) Unwrap added in v1.0.2

func (e *RequestPreparationError) Unwrap() error

type RequestStream

type RequestStream struct {
	// contains filtered or unexported fields
}

A RequestStream is a low-level abstraction representing an HTTP/3 request stream. It decouples sending of the HTTP request from reading the HTTP response, allowing the application to optimistically use the stream (and, for example, send datagrams) before receiving the response.

This is only needed for advanced use case, e.g. WebTransport and the various MASQUE proxying protocols. Stream and application errors are returned as *Error, possibly wrapped.

func (*RequestStream) CancelRead

func (s *RequestStream) CancelRead(errorCode quic.StreamErrorCode)

CancelRead aborts receiving on this stream. See quic.Stream.CancelRead for more details.

func (*RequestStream) CancelWrite

func (s *RequestStream) CancelWrite(errorCode quic.StreamErrorCode)

CancelWrite aborts sending on this stream. See quic.Stream.CancelWrite for more details.

func (*RequestStream) Close

func (s *RequestStream) Close() error

Close closes the send-direction of the stream. It does not close the receive-direction of the stream.

func (*RequestStream) Context

func (s *RequestStream) Context() context.Context

Context returns a context derived from the underlying QUIC stream's context. See quic.Stream.Context for more details.

func (*RequestStream) QlogTrace

func (s *RequestStream) QlogTrace() qlogwriter.Trace

QlogTrace returns the qlog trace of the underlying QUIC connection. It is nil if qlog is not enabled.

func (*RequestStream) Read

func (s *RequestStream) Read(b []byte) (int, error)

Read reads data from the underlying stream.

It can only be used after the request has been sent using RequestStream.SendRequestHeader and RequestStream.ReadResponse has returned the response.

func (*RequestStream) ReadResponse

func (s *RequestStream) ReadResponse() (*http.Response, error)

ReadResponse reads the HTTP response from the stream.

It must be called after sending the request using RequestStream.SendRequestHeader. It is invalid to call it more than once. It doesn't set http.Response.Request or http.Response.TLS.

func (*RequestStream) ReceiveDatagram

func (s *RequestStream) ReceiveDatagram(ctx context.Context) ([]byte, error)

ReceiveDatagram receives HTTP Datagrams (RFC 9297).

It is only possible if HTTP Datagram support was enabled using Transport.EnableDatagrams.

func (*RequestStream) SendDatagram

func (s *RequestStream) SendDatagram(b []byte) error

SendDatagram sends a new HTTP Datagram (RFC 9297).

It is only possible to send datagrams if the server enabled support for this extension. It is recommended (though not required) to send the request before calling this method, as the server might drop datagrams which it can't associate with an existing request.

func (*RequestStream) SendRequestHeader

func (s *RequestStream) SendRequestHeader(req *http.Request) error

SendRequestHeader sends the HTTP request.

It can only be used for requests that don't have a request body. It is invalid to call it more than once.

func (*RequestStream) SetDeadline

func (s *RequestStream) SetDeadline(t time.Time) error

SetDeadline sets the read and write deadlines associated with the stream. It is equivalent to calling both RequestStream.SetReadDeadline and RequestStream.SetWriteDeadline.

func (*RequestStream) SetPriority

func (s *RequestStream) SetPriority(urgency int8, incremental bool)

SetPriority configures local scheduling of data sent on this request stream. It delegates to the official quic-go stream scheduler.

func (*RequestStream) SetReadDeadline

func (s *RequestStream) SetReadDeadline(t time.Time) error

SetReadDeadline sets the deadline for RequestStream.Read calls.

func (*RequestStream) SetWriteDeadline

func (s *RequestStream) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the deadline for RequestStream.Write calls.

func (*RequestStream) StreamID

func (s *RequestStream) StreamID() quic.StreamID

StreamID returns the QUIC stream ID of the underlying QUIC stream.

func (*RequestStream) TryWriteAll

func (s *RequestStream) TryWriteAll(b []byte) error

TryWriteAll writes b if the entire DATA frame can be queued immediately. It can only be used after the request has been sent using RequestStream.SendRequestHeader.

func (*RequestStream) UpdatePriority added in v1.0.5

func (s *RequestStream) UpdatePriority(urgency int8, incremental bool) error

UpdatePriority changes the peer's response priority after SendRequestHeader. SetPriority instead controls local QUIC upload scheduling.

func (*RequestStream) Write

func (s *RequestStream) Write(b []byte) (int, error)

Write writes data to the stream.

It can only be used after the request has been sent using RequestStream.SendRequestHeader.

type RoundTripOpt

type RoundTripOpt struct {

	// OnlyCachedConn controls whether the Transport may create a new QUIC connection.
	// If true and no cached connection is available, [Transport.RoundTripOpt] returns [ErrNoCachedConn].
	OnlyCachedConn bool
	// contains filtered or unexported fields
}

RoundTripOpt contains options for Transport.RoundTripOpt.

type Server

type Server struct {
	// Addr optionally specifies the UDP address for the server to listen on,
	// in the form "host:port".
	//
	// When used by [Server.ListenAndServe] and [Server.ListenAndServeTLS], if empty,
	// ":https" (port 443) is used. See [net.Dial] for details of the address
	// format.
	//
	// Otherwise, if Port is not set and underlying QUIC listeners do not
	// have valid port numbers, the port part is used in Alt-Svc headers set
	// with [Server.SetQUICHeaders].
	Addr string

	// Port is used in Alt-Svc response headers set with [Server.SetQUICHeaders]. If
	// needed Port can be manually set when the Server is created.
	//
	// This is useful when a Layer 4 firewall is redirecting UDP traffic and
	// clients must use a port different from the port the Server is
	// listening on.
	Port int

	// TLSConfig provides a TLS configuration for use by server. It must be
	// set for [Server.ListenAndServe] and [Server.Serve].
	TLSConfig *tls.Config

	// QUICConfig provides the parameters for QUIC connections created with [Server.Serve].
	// If nil, it uses reasonable default values.
	QUICConfig *quic.Config

	// Handler is the HTTP request handler. If nil, [http.DefaultServeMux] is used.
	Handler http.Handler

	// EnableDatagrams enables support for HTTP/3 datagrams (RFC 9297).
	// For connections created by the server, this also enables [quic.Config.EnableDatagrams].
	EnableDatagrams bool

	// MaxHeaderBytes controls the maximum number of bytes the server will
	// read parsing the request HEADERS frame. It does not limit the size of
	// the request body. If zero or negative, [http.DefaultMaxHeaderBytes] is
	// used.
	MaxHeaderBytes int

	// AdditionalSettings specifies additional HTTP/3 settings.
	// It is invalid to specify any settings defined by RFC 9114 (HTTP/3) and RFC 9297 (HTTP Datagrams).
	AdditionalSettings g.MapOrd[uint64, uint64]

	// ReadHeaderTimeout limits the time to read each request's headers.
	// Zero or negative values disable this timeout.
	ReadHeaderTimeout time.Duration

	// IdleTimeout specifies how long until idle clients connection should be
	// closed. Idle refers only to the HTTP/3 layer, activity at the QUIC layer
	// like PING frames are not considered.
	// If zero or negative, there is no timeout.
	IdleTimeout time.Duration

	// ConnContext optionally specifies a function that modifies the context used for a new connection c.
	// The provided ctx has a ServerContextKey value.
	ConnContext func(ctx context.Context, c *quic.Conn) context.Context

	Logger *slog.Logger
	// contains filtered or unexported fields
}

Server is a HTTP/3 server.

func (*Server) Close

func (s *Server) Close() error

Close closes the server immediately, aborting requests and sending CONNECTION_CLOSE frames to connected clients. Calling Close concurrently with Server.ListenAndServe may race with UDP socket creation; use Server.Serve to avoid this. It is the caller's responsibility to close any connection passed to Server.ServeQUICConn.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe() error

ListenAndServe listens on the UDP address Server.Addr and calls Server.Handler to handle HTTP/3 requests on incoming connections.

If Server.Addr is blank, ":https" is used.

func (*Server) ListenAndServeTLS

func (s *Server) ListenAndServeTLS(certFile, keyFile string) error

ListenAndServeTLS listens on the UDP address Server.Addr and calls Server.Handler to handle HTTP/3 requests on incoming connections.

If Server.Addr is blank, ":https" is used.

func (*Server) NewRawServerConn

func (s *Server) NewRawServerConn(conn *quic.Conn) (*RawServerConn, error)

func (*Server) Serve

func (s *Server) Serve(conn net.PacketConn) error

Serve an existing UDP connection. It is possible to reuse the same connection for outgoing connections. Closing the server does not close the connection.

func (*Server) ServeListener

func (s *Server) ServeListener(ln QUICListener) error

ServeListener serves an existing QUIC listener. Use ConfigureTLSConfig to configure a tls.Config for the QUIC listener. Closing the server does not close the listener; closing the listener is the application's responsibility. ServeListener always returns a non-nil error. After Server.Shutdown or Server.Close, it returns http.ErrServerClosed.

func (*Server) ServeQUICConn

func (s *Server) ServeQUICConn(conn *quic.Conn) error

ServeQUICConn serves a single QUIC connection.

func (*Server) SetQUICHeaders

func (s *Server) SetQUICHeaders(hdr http.Header) error

SetQUICHeaders can be used to set the proper headers that announce that this server supports HTTP/3. The values set by default advertise all the ports the server is listening on, but can be changed to a specific port by setting Server.Port before launching the server. If none of the server's listeners report a valid port through QUICListener.Addr, Server.Addr is used to extract the port, if specified. For example, a server launched using Server.ListenAndServe on an address with port 443 would set:

Alt-Svc: h3=":443"; ma=2592000

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server without interrupting any active connections. The server sends a GOAWAY frame first, then waits for all running requests to complete. Calling Shutdown concurrently with Server.ListenAndServe may race with UDP socket creation; use Server.Serve to avoid this.

type Settings

type Settings struct {
	// MaxFieldSectionSize bounds uncompressed field sections sent to this peer.
	// A negative value means the peer omitted the setting; zero is a real limit.
	MaxFieldSectionSize int64
	// Support for HTTP/3 datagrams (RFC 9297)
	EnableDatagrams bool
	// Extended CONNECT, RFC 9220
	EnableExtendedConnect bool
	// Other settings, defined by the application
	Other g.MapOrd[uint64, uint64]
}

Settings are HTTP/3 settings that apply to the underlying connection.

func ClientSessionSettings added in v1.0.23

func ClientSessionSettings(session *tls.ClientSessionState) (*Settings, bool)

ClientSessionSettings returns a private snapshot of the server SETTINGS saved with this exact TLS ticket. It does not validate TLS lifetime or authenticity. Missing, malformed and duplicate metadata returns false; TLS owns validation.

type Settingser

type Settingser interface {
	// ReceivedSettings returns a channel that is closed once the peer's SETTINGS frame was received.
	// The settings can be obtained from [Settingser.Settings] after the channel is closed.
	ReceivedSettings() <-chan struct{}
	// Settings returns the settings received on this connection.
	// It is only valid to call this method after the channel returned by [Settingser.ReceivedSettings] is closed.
	Settings() *Settings
}

Settingser allows waiting for and retrieving the peer's HTTP/3 settings.

type Stream

type Stream struct {
	// contains filtered or unexported fields
}

A Stream is an HTTP/3 stream.

When writing to and reading from the stream, data is framed in HTTP/3 DATA frames.

func (*Stream) QlogTrace

func (s *Stream) QlogTrace() qlogwriter.Trace

QlogTrace returns the qlog trace of the underlying QUIC connection. It is nil if qlog is not enabled.

func (*Stream) Read

func (s *Stream) Read(b []byte) (int, error)

func (*Stream) ReceiveDatagram

func (s *Stream) ReceiveDatagram(ctx context.Context) ([]byte, error)

func (*Stream) SendDatagram

func (s *Stream) SendDatagram(b []byte) error

func (*Stream) StreamID

func (s *Stream) StreamID() quic.StreamID

func (*Stream) TryWriteAll

func (s *Stream) TryWriteAll(b []byte) error

TryWriteAll writes b in a DATA frame if the entire frame can be queued immediately. It returns quic.ErrWouldBlock without queueing anything otherwise. It can only be used after the response header has been sent.

func (*Stream) Write

func (s *Stream) Write(b []byte) (int, error)

Write writes data to the stream.

It can only be used after the response header has been sent.

type StreamPriority

type StreamPriority struct {
	Urgency     int8
	Incremental bool
}

StreamPriority configures local QUIC scheduling of request stream data. Urgency is clipped to 0 through 7, with smaller values taking priority. Incremental selects round-robin scheduling within the urgency level. This calls quic.Stream.SetPriority; it does not send a PRIORITY_UPDATE frame or change the request's Priority header.

type StreamType

type StreamType uint64

StreamType is the stream type of a unidirectional stream.

type Transport

type Transport struct {
	// InitialPeerSettings supplies authenticated settings before ordinary request
	// headers and control-stream SETTINGS are applied. It runs once per HTTP/3
	// protocol generation, after TLS completion. The result is copied. It must
	// be fast, concurrency safe, not perform I/O or reenter the transport.
	// Early requests do not wait for or initialize this callback.
	InitialPeerSettings func(*quic.Conn) (g.MapOrd[uint64, uint64], error)
	// PrepareHeaders runs on a private request/header clone for each RoundTrip
	// attempt after connection selection and normal TLS/settings initialization,
	// before a request stream or body read. It may change Header and derive the
	// request Context only. Errors are terminal RequestPreparationErrors.
	// IsEarlyRequest reports the frozen path that skipped authenticated
	// initialization, independently of packet encryption or handshake timing.
	// Raw OpenRequestStream callers retain explicit header ownership. The callback
	// must be fast, concurrency safe, not perform I/O or reenter the transport.
	PrepareHeaders func(*http.Request, *quic.Conn) error
	// ConnectionPoolPartition partitions both exact-authority lookup and
	// cross-authority reuse. The authority is always included in the actual key.
	// It must be pure, concurrency safe, stable for an attempt and not reenter
	// the transport. Nil retains the native single-partition pool.
	ConnectionPoolPartition func(context.Context, string) string
	// ConnectionReusePolicy may authorize an established connection for another
	// authority. The callback owns certificate, route and privacy checks. Only
	// live, handshake-complete, non-draining native clients are considered; nil
	// retains the native per-authority pool. It runs outside pool locks, may run
	// concurrently and must respect ctx. Preconnect invokes the same policy.
	ConnectionReusePolicy func(context.Context, ConnectionReuseInfo) bool
	// EarlyDataRestart keeps a rejected 0-RTT connection and recreates HTTP/3
	// protocol state after verified TLS. Replayable requests restart once;
	// the default preserves the caller-managed rejection behavior.
	// This option applies to pooled RoundTrip connections.
	EarlyDataRestart bool
	// TLSClientConfig specifies the TLS configuration to use with
	// [tls.Client]. If nil, the default configuration is used.
	TLSClientConfig *tls.Config

	// QUICConfig is the [quic.Config] used for dialing new connections.
	// If nil, reasonable default values will be used.
	QUICConfig *quic.Config

	// Dial specifies an optional dial function for creating QUIC
	// connections for requests.
	// If [Transport.Dial] is nil, a [net.UDPConn] will be created at the first request
	// and will be reused for subsequent connections to other servers.
	Dial func(ctx context.Context, addr string, tlsCfg *tls.Config, cfg *quic.Config) (*quic.Conn, error)

	// Enable support for HTTP/3 datagrams (RFC 9297).
	// If [Transport.QUICConfig] is set, [quic.Config.EnableDatagrams] must also be enabled.
	EnableDatagrams bool

	// Additional HTTP/3 settings.
	// It is invalid to specify any settings defined by RFC 9114 (HTTP/3) and RFC 9297 (HTTP Datagrams).
	AdditionalSettings g.MapOrd[uint64, uint64]

	// MaxResponseHeaderBytes specifies a limit on how many response bytes are
	// allowed in the server's response header.
	// Zero means to use a default limit.
	MaxResponseHeaderBytes int

	// DisableCompression, if true, prevents the Transport from requesting compression with an
	// "Accept-Encoding: gzip" request header when the Request contains no existing Accept-Encoding value.
	// If the Transport requests gzip on its own and gets a gzipped response, it's transparently
	// decoded in the Response.Body.
	// However, if the user explicitly requested gzip it is not automatically uncompressed.
	DisableCompression bool

	// StreamPriority optionally overrides the local scheduling priority of new
	// request streams. Nil preserves quic-go's default scheduling.
	StreamPriority *StreamPriority

	// QPACKConfig optionally controls request compression, critical streams and
	// capacity announcements. DynamicTable enables dynamic request encoding.
	QPACKConfig *QPACKConfig

	// WireConfig optionally controls reserved frames and request priority updates.
	WireConfig *WireConfig

	Logger *slog.Logger
	// contains filtered or unexported fields
}

Transport implements the http.RoundTripper interface.

func (*Transport) Close

func (t *Transport) Close() error

Close closes the QUIC connections that this Transport has used. A Transport cannot be used after it has been closed.

func (*Transport) CloseIdleConnections

func (t *Transport) CloseIdleConnections()

CloseIdleConnections closes any QUIC connections in the transport's pool that are currently idle. An idle connection is one that was previously used for requests but is now sitting unused. This method does not interrupt any connections currently in use. It also does not affect connections obtained via Transport.NewClientConn.

func (*Transport) HasCachedConnection added in v1.0.29

func (t *Transport) HasCachedConnection(ctx context.Context, address string) bool

HasCachedConnection reports whether address has a confirmed reusable session in this context's exact pool partition. It does not dial, resolve aliases, reserve a request or invoke the cross-origin reuse policy. The result is a snapshot: normal request admission still handles concurrent closure/GOAWAY.

func (*Transport) NewClientConn

func (t *Transport) NewClientConn(conn *quic.Conn) *ClientConn

NewClientConn creates a new HTTP/3 client connection on top of a QUIC connection. Most users should use Transport.RoundTrip instead of creating a connection directly. Specifically, it is not needed to perform GET, POST, HEAD and CONNECT requests.

Obtaining a ClientConn is only needed for more advanced use cases, such as using Extended CONNECT for WebTransport or the various MASQUE protocols.

func (*Transport) NewRawClientConn

func (t *Transport) NewRawClientConn(conn *quic.Conn) *RawClientConn

NewRawClientConn creates a new low-level HTTP/3 client connection on top of a QUIC connection. Unlike Transport.NewClientConn, the returned RawClientConn allows the application to take control of the stream accept loops by calling RawClientConn.HandleUnidirectionalStream for incoming unidirectional streams and ClientConn.HandleBidirectionalStream for incoming bidirectional streams.

func (*Transport) Preconnect added in v1.0.10

func (t *Transport) Preconnect(ctx context.Context, address string) error

Preconnect prepares a pooled HTTP/3 connection to address (host:port), waiting for the verified TLS handshake without sending an HTTP request. Connection SETTINGS and stream setup retain the transport's normal behavior. Cancellation releases this caller; a shared connection used by another caller is retained. Otherwise a failed or abandoned attempt is removed and closed.

func (*Transport) PreconnectEarly added in v1.0.18

func (t *Transport) PreconnectEarly(ctx context.Context, address string) (*quic.Conn, error)

PreconnectEarly prepares a pooled connection without sending an HTTP request. It returns when cached 0-RTT keys are available, or after the full handshake when early data is unavailable. The returned connection remains owned by the transport. Early readiness does not authenticate the current handshake. A custom Dial callback must itself support returning an early connection.

func (*Transport) PreconnectWithOptions added in v1.0.29

func (t *Transport) PreconnectWithOptions(
	ctx context.Context,
	address string,
	options PreconnectOptions,
) (*quic.Conn, error)

PreconnectWithOptions prepares the normal pooled connection with an optional start notification. It preserves Preconnect's shared-dial and cancellation ownership. It never reads or sends an application request.

func (*Transport) RetireConnections added in v1.0.31

func (t *Transport) RetireConnections()

RetireConnections removes current connections from request lookup. Existing streams finish normally and their connections then close. Idle connections and pending handshakes close immediately. It does not send GOAWAY, clear TLS tickets or prevent future use of the transport. Connections obtained through NewClientConn are application-owned and are not included.

func (*Transport) RoundTrip

func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip does a round trip.

func (*Transport) RoundTripCached added in v1.0.25

func (t *Transport) RoundTripCached(req *http.Request) (*http.Response, error)

RoundTripCached uses an existing connection for the initial attempt. An exact ErrNoCachedConn leaves Request.Body open and caller-owned; no request was sent. All other outcomes transfer body ownership as in RoundTrip. Once a cached attempt starts, normal retry rules may establish a dedicated connection.

func (*Transport) RoundTripCachedReady added in v1.0.29

func (t *Transport) RoundTripCachedReady(req *http.Request) (*http.Response, error)

RoundTripCachedReady uses only a confirmed reusable connection for the first attempt. A pending dial, early-only readiness or GOAWAY is an ErrNoCachedConn miss without waiting or taking body ownership. Normal retry rules can dial after a confirmed initial attempt has started. RoundTripCached retains its existing behavior of joining pending cached attempts.

func (*Transport) RoundTripOpt

func (t *Transport) RoundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Response, error)

RoundTripOpt is like Transport.RoundTrip, but takes options.

type WireConfig added in v1.0.2

type WireConfig struct {
	// OnControlFrame handles otherwise unknown frames after the peer's SETTINGS.
	// The reader is limited to this frame and valid only during the callback.
	// Unread bytes are drained; a truncated payload or callback error closes the
	// connection with H3_FRAME_ERROR. Calls are serialized per control stream.
	// It must not reenter this connection. Nil keeps native extension handling.
	OnControlFrame func(*quic.Conn, ControlFrame) error
	// OnResponseHeaders runs after each valid response header block, including
	// informational responses, before tracing or delivery to the application.
	// An error aborts the request. The callback must return promptly, must not
	// mutate the request or response or read its body, and must be safe for
	// concurrent requests. Nil leaves response handling unchanged.
	OnResponseHeaders func(*http.Request, *http.Response) error
	// CoalesceInitialSettings stages control-stream data before the first
	// application flight when peer credit allows. With early keys, setup runs
	// before Initial packetization unless FlushEarlySettings is enabled.
	// Backpressure keeps asynchronous writes on the same stream. Factories must not block.
	CoalesceInitialSettings bool
	// FlushEarlySettings stages initial control data and attempts to flush it
	// before releasing a resumed early connection to requests. The Initial flight
	// gets its own send opportunity first. Congestion and pacing can defer either
	// write; packet counts and delivery are not fixed. Does not enable early data.
	FlushEarlySettings bool
	// CoalesceRequestHeaders stages initial priority, ready QPACK encoder
	// instructions, request HEADERS and a bodyless request's FIN in one
	// connection-loop turn. Congestion and packet size limits still apply.
	// Busy or blocked critical streams retain their asynchronous owner.
	CoalesceRequestHeaders bool
	// RequestBodyBufferSize controls reads from request bodies. Zero uses 8 KiB.
	RequestBodyBufferSize int
	// RequestBodyBufferSizePolicy overrides the fixed size for a request body.
	// It receives ContentLength (-1 if unknown) and must be concurrency safe.
	// Returning zero selects the default. Valid sizes are at most 16 MiB.
	RequestBodyBufferSizePolicy func(contentLength int64) int
	// RequestBodyFirstReadSizePolicy caps the first nonempty body read. Zero
	// uses BufferSize. Results must be between zero and BufferSize. It runs
	// before request bytes or QPACK state changes and must be concurrency safe.
	RequestBodyFirstReadSizePolicy func(RequestBodyReadInfo) int
	// MaxDataFrameSize limits request DATA payloads. Zero preserves one frame
	// per Write. This does not control QUIC packet boundaries.
	MaxDataFrameSize int

	// SettingsGrease generates one reserved SETTINGS identifier/value per
	// connection, before any control-stream bytes. Nil adds nothing. The callback
	// must not block or reenter the transport. IDs must be 0x1f*N+0x21 and both
	// values must fit QUIC integers. It cannot replace existing settings.
	SettingsGrease func() (uint64, uint64, error)

	// ControlGreaseFrames runs once per connection, after SETTINGS.
	ControlGreaseFrames func() ([]GreaseFrame, error)
	// RequestGreaseFrames runs before each request's HEADERS, on its stream.
	RequestGreaseFrames func(*http.Request) ([]GreaseFrame, error)
	// SendPriorityUpdates sends the request's explicit Priority field on the
	// control stream when it differs from RFC 9218's default (u=3, i=?0).
	// It never invents a Priority header and is independent of GREASE.
	// Recognized urgency/incremental parameters are serialized canonically.
	SendPriorityUpdates bool
	// CompactPriorityUpdates omits the space after commas in RFC 9218 fields.
	CompactPriorityUpdates bool
}

WireConfig adds optional client wire behavior. Nil preserves upstream behavior. Factories may run concurrently on different connections and must not mutate requests or reenter the transport. Returned payloads are copied before use.

func (*WireConfig) Clone added in v1.0.2

func (c *WireConfig) Clone() *WireConfig

func (*WireConfig) Validate added in v1.0.5

func (c *WireConfig) Validate() error

Validate checks allocation and frame size limits without calling factories.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL