Documentation
¶
Overview ¶
Package websocket implements RFC 6455 and RFC 7692 WebSocket clients, servers, framing, masking, message assembly, close validation, and bounded decompression.
Dial and Upgrade are the normal transport entry points. Message is a closed Go+ sum type, so applications handle text, binary, ping, pong, and close without integer message-kind constants. Conn permits one concurrent reader and one concurrent writer and serializes writes to prevent frame interleave.
Low-level users can use ParseHeader, AppendHeader, Mask, and Assembler. Those APIs contain the same validation used by Conn and are allocation-free on the framing hot path.
Package websocket implements RFC 6455 WebSocket framing and transport. The semantic layer is authored in Go+; hot framing paths remain small, allocation-free Go functions so both Go+ and Go callers get the same wire.
Index ¶
- Variables
- func AcceptKey(key string) string
- func AppendClosePayload(dst []byte, code CloseCode, reason string) ([]byte, error)
- func AppendFrame(dst []byte, h Header, payload []byte) ([]byte, error)
- func AppendHeader(dst []byte, h Header) ([]byte, error)
- func CapabilityFold[R any](v Capability, cs CapabilityCases[R]) R
- func FailureEqual(a, b Failure) bool
- func FailureEqualWith(a, b Failure, ov FailureEqOverrides) bool
- func FailureFold[R any](f Failure, cs FailureCases[R]) R
- func IsControl(op Opcode) bool
- func IsRFC8441Request(r *http.Request) bool
- func IsRFC9220Request(r *http.Request) bool
- func Mask(payload []byte, key [4]byte, offset int) int
- func PhaseEqual(a, b Phase) bool
- func PhaseEqualWith(a, b Phase, ov PhaseEqOverrides) bool
- func PhaseFold[R any](p Phase, cs PhaseCases[R]) R
- func SameOrigin(r *http.Request) bool
- func Serve(listener net.Listener, handler func(*Conn)) error
- func ValidCloseCode(code CloseCode) bool
- func ValidOpcode(op Opcode) bool
- func ValidateServerRequest(r *http.Request) (string, error)
- type Assembler
- type BinaryMessage
- type Capability
- type CapabilityCases
- type CloseAttempt
- type CloseCode
- type CloseFailed
- type CloseMessage
- type CloseReceivedPhase
- type CloseReceivedSession
- type CloseSentCapability
- type CloseSentPhase
- type CloseSentSession
- type CloseStarted
- type ClosedCapability
- type ClosedPhase
- type ClosedSession
- type CompressionOptions
- type Conn
- func (c *Conn) Close() error
- func (c *Conn) HandshakeProtocol() HandshakeProtocol
- func (c *Conn) NetConn() net.Conn
- func (c *Conn) ReadMessage() (Message, error)
- func (c *Conn) SetDeadline(t time.Time) error
- func (c *Conn) SetReadDeadline(t time.Time) error
- func (c *Conn) SetWriteDeadline(t time.Time) error
- func (c *Conn) WriteBinary(payload []byte) error
- func (c *Conn) WriteBinaryOwned(payload []byte) error
- func (c *Conn) WriteClose(code CloseCode, reason string) error
- func (c *Conn) WriteMessage(message Message) error
- func (c *Conn) WriteMessageOwned(message Message) error
- func (c *Conn) WritePing(payload []byte) error
- func (c *Conn) WritePong(payload []byte) error
- func (c *Conn) WriteText(payload []byte) error
- func (c *Conn) WriteTextOwned(payload []byte) error
- type ConnConfig
- type ConnectingPhase
- type ConnectingSession
- type ControlFragmented
- type ControlTooLarge
- type DialOptions
- type ExpectedContinuation
- type Failure
- type FailureCases
- type FailureEqOverrides
- type HTTP2Mode
- type HTTP3Mode
- type HandshakeProtocol
- type HandshakeRejected
- type Header
- type InvalidCloseCode
- type InvalidClosePayload
- type InvalidOpcode
- type InvalidUTF8
- type Lin
- type Message
- type MessageTooLarge
- type NeedMoreData
- type NonCanonicalLength
- type Opcode
- type OpenCapability
- type OpenPhase
- type OpenSession
- type Phase
- type PhaseCases
- type PhaseEqOverrides
- type PingMessage
- type PongMessage
- type ReservedBits
- type Session
- type Side
- type TextMessage
- type TransportFailed
- type UnexpectedContinuation
- type UpgradeOptions
- type WrongMask
Constants ¶
This section is empty.
Variables ¶
var ( ErrNeedMoreData = io.ErrUnexpectedEOF ErrInvalidOpcode = errors.New("websocket: invalid opcode") ErrReservedBits = errors.New("websocket: reserved bits set") ErrWrongMask = errors.New("websocket: incorrect masking for peer role") ErrNonCanonicalLength = errors.New("websocket: non-canonical payload length") ErrControlFragmented = errors.New("websocket: fragmented control frame") ErrControlTooLarge = errors.New("websocket: control payload exceeds 125 bytes") ErrInvalidLength = errors.New("websocket: invalid payload length") )
var ( ErrUnexpectedContinuation = errors.New("websocket: unexpected continuation") ErrExpectedContinuation = errors.New("websocket: expected continuation") ErrInvalidUTF8 = errors.New("websocket: invalid UTF-8") ErrInvalidClosePayload = errors.New("websocket: invalid close payload") ErrInvalidCloseCode = errors.New("websocket: invalid close code") ErrMessageTooLarge = errors.New("websocket: message exceeds configured limit") )
var ErrHandshake = errors.New("websocket: invalid opening handshake")
var ErrInvalidExtension = errors.New("websocket: invalid extension negotiation")
Functions ¶
func AcceptKey ¶
AcceptKey computes Sec-WebSocket-Accept without heap allocation except for the returned string.
func AppendClosePayload ¶
func AppendFrame ¶ added in v0.18.1
AppendFrame appends a complete frame to dst. It copies payload and applies the mask to the appended copy, preserving caller ownership. Reusing dst makes complete frame construction allocation-free.
func AppendHeader ¶
AppendHeader validates h and appends its canonical wire representation. It allocates only when dst lacks capacity.
func CapabilityFold ¶ added in v0.18.1
func CapabilityFold[R any](v Capability, cs CapabilityCases[R]) R
CapabilityFold reduces Capability by one-level case analysis.
func FailureEqual ¶
FailureEqual reports structural equality of a and b.
func FailureEqualWith ¶
func FailureEqualWith(a, b Failure, ov FailureEqOverrides) bool
FailureEqualWith reports structural equality of a and b under ov.
func FailureFold ¶
func FailureFold[R any](f Failure, cs FailureCases[R]) R
FailureFold reduces Failure by one-level case analysis.
func IsRFC8441Request ¶ added in v0.19.0
IsRFC8441Request reports whether r is an HTTP/2 WebSocket extended CONNECT request. It does not imply that the rest of the opening handshake is valid.
func IsRFC9220Request ¶ added in v0.20.0
IsRFC9220Request reports whether r is an HTTP/3 WebSocket extended CONNECT request. It does not imply that the rest of the handshake is valid.
func PhaseEqual ¶
PhaseEqual reports structural equality of a and b.
func PhaseEqualWith ¶
func PhaseEqualWith(a, b Phase, ov PhaseEqOverrides) bool
PhaseEqualWith reports structural equality of a and b under ov.
func PhaseFold ¶
func PhaseFold[R any](p Phase, cs PhaseCases[R]) R
PhaseFold reduces Phase by one-level case analysis.
func SameOrigin ¶
SameOrigin accepts non-browser clients without Origin and otherwise requires the Origin host to match the HTTP Host header. Pass it as UpgradeOptions.CheckOrigin for browser-facing endpoints.
func Serve ¶
Serve accepts raw TCP connections and applies handler after an HTTP upgrade. It is intentionally small; net/http Upgrade is the preferred server API.
func ValidCloseCode ¶
func ValidOpcode ¶
Types ¶
type Assembler ¶
type Assembler struct {
MaxMessage int64
// contains filtered or unexported fields
}
Assembler validates fragmentation and turns frames into complete messages. A nil message means a non-final data fragment was accepted.
type BinaryMessage ¶
type BinaryMessage struct {
Payload []byte
}
type Capability ¶ added in v0.18.1
type Capability interface {
// contains filtered or unexported methods
}
Capability is the Go+ ownership-oriented API. Go callers that do not want typestate use Conn directly.
func FinishClose ¶ added in v0.18.1
func FinishClose(capability Lin[Capability]) (Capability, error)
func Send ¶ added in v0.18.1
func Send(capability Lin[Capability], message Message) (Capability, error)
Send consumes and returns the open capability, preventing concurrent or accidental duplicated ownership in Go+ orchestration.
type CapabilityCases ¶ added in v0.18.1
type CapabilityCases[R any] struct { OpenCapability func(conn *Conn) R CloseSentCapability func(conn *Conn) R ClosedCapability func(conn *Conn) R }
CapabilityCases selects one handler per Capability variant for CapabilityFold.
type CloseAttempt ¶ added in v0.18.1
type CloseAttempt interface {
// contains filtered or unexported methods
}
CloseAttempt preserves ownership on both the success and failure paths.
func BeginClose ¶ added in v0.18.1
func BeginClose(capability Lin[Capability], code CloseCode, reason string) CloseAttempt
type CloseCode ¶
type CloseCode uint16
const ( CloseNormalClosure CloseCode = 1000 CloseGoingAway CloseCode = 1001 CloseProtocolError CloseCode = 1002 CloseUnsupportedData CloseCode = 1003 CloseInvalidPayload CloseCode = 1007 ClosePolicyViolation CloseCode = 1008 CloseMessageTooBig CloseCode = 1009 CloseMandatoryExt CloseCode = 1010 CloseInternalError CloseCode = 1011 )
type CloseFailed ¶ added in v0.18.1
type CloseFailed struct {
Capability Capability
Err error
}
type CloseMessage ¶
type CloseReceivedPhase ¶
type CloseReceivedPhase struct{}
type CloseReceivedSession ¶
type CloseReceivedSession struct{}
type CloseSentCapability ¶ added in v0.18.1
type CloseSentCapability struct {
Conn *Conn
}
type CloseSentPhase ¶
type CloseSentPhase struct{}
type CloseSentSession ¶
type CloseSentSession struct{}
type CloseStarted ¶ added in v0.18.1
type CloseStarted struct {
Capability Capability
}
type ClosedCapability ¶ added in v0.18.1
type ClosedCapability struct {
Conn *Conn
}
type ClosedPhase ¶
type ClosedPhase struct{}
type ClosedSession ¶
type ClosedSession struct{}
type CompressionOptions ¶
type CompressionOptions struct {
ClientMaxWindowBits int
ServerMaxWindowBits int
AllowClientContextTakeover bool
AllowServerContextTakeover bool
}
CompressionOptions enables RFC 7692 permessage-deflate. Window-bit values are zero (do not advertise) or 8..15. This implementation always negotiates no-context-takeover in both directions, making each message independently decodable and bounding memory retained between messages.
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
Conn is a concurrency-safe WebSocket connection. One reader and one writer may operate concurrently; writes are serialized so frames never interleave.
func Dial ¶
Dial opens a WebSocket using RFC 8441 when selected and RFC 6455 otherwise. On success the returned response is metadata only; Conn exclusively owns the underlying transport stream, so callers may safely ignore response.Body.
func NewConn ¶
func NewConn(rw io.ReadWriteCloser, side Side, buffered *bufio.Reader, cfg ConnConfig) *Conn
func Upgrade ¶
func Upgrade(w http.ResponseWriter, r *http.Request, opts UpgradeOptions) (*Conn, string, error)
Upgrade accepts an RFC 6455 HTTP/1.1 request and preserves bytes already buffered after the handshake.
func (*Conn) HandshakeProtocol ¶ added in v0.19.0
func (c *Conn) HandshakeProtocol() HandshakeProtocol
HandshakeProtocol reports whether RFC 6455 Upgrade or RFC 8441 extended CONNECT established the connection.
func (*Conn) ReadMessage ¶
ReadMessage returns the next complete data or close message. Ping is answered automatically; Pong is surfaced so applications can track liveness.
func (*Conn) WriteBinary ¶ added in v0.18.1
func (*Conn) WriteBinaryOwned ¶ added in v0.18.1
func (*Conn) WriteClose ¶ added in v0.18.1
WriteClose starts the RFC 6455 closing handshake without immediately closing the underlying transport.
func (*Conn) WriteMessage ¶
func (*Conn) WriteMessageOwned ¶
WriteMessageOwned may mask the message payload in place on client connections. Callers that transfer ownership can use it to avoid the one defensive payload copy required by WriteMessage.
func (*Conn) WriteText ¶ added in v0.18.1
WriteText and WriteBinary are concise Go-facing forms of WriteMessage.
func (*Conn) WriteTextOwned ¶ added in v0.18.1
WriteTextOwned and WriteBinaryOwned transfer payload ownership, allowing a client connection to mask in place instead of making a defensive copy.
type ConnConfig ¶
type ConnectingPhase ¶
type ConnectingPhase struct{}
type ConnectingSession ¶
type ConnectingSession struct{}
type ControlFragmented ¶
type ControlFragmented struct{}
type ControlTooLarge ¶
type ControlTooLarge struct{}
type DialOptions ¶
type DialOptions struct {
Protocols []string
Header http.Header
TLSConfig *tls.Config
NetDialer *net.Dialer
// DialContext overrides TCP connection establishment, enabling proxies,
// custom transports, and deterministic fault injection.
DialContext func(context.Context, string, string) (net.Conn, error)
Config ConnConfig
Compression *CompressionOptions
// HTTP3 controls RFC 9220 extended CONNECT. Auto tries HTTP/3 when an
// HTTP3Transport supplies learned origin capability, then falls back to
// HTTP/2 and HTTP/1.1 when the transport is unavailable. HTTP/3 always
// uses TLS.
HTTP3 HTTP3Mode
// HTTP3Transport optionally supplies a shared HTTP/3 transport. The
// transport must support extended CONNECT and a streaming request body.
HTTP3Transport http.RoundTripper
// QUICConfig configures QUIC when the package owns the HTTP/3 transport.
QUICConfig *quic.Config
// HTTP2 controls RFC 8441 extended CONNECT. Auto prefers HTTP/2 for wss
// URLs and transparently falls back to RFC 6455. Cleartext ws remains on
// HTTP/1.1 unless HTTP2Only is selected.
HTTP2 HTTP2Mode
// HTTP2Transport optionally supplies a shared HTTP/2-capable transport.
// It must preserve a streaming request body and response body.
HTTP2Transport http.RoundTripper
}
type ExpectedContinuation ¶
type ExpectedContinuation struct{}
type Failure ¶
type Failure interface {
// contains filtered or unexported methods
}
Failure classifies protocol failure without string matching.
type FailureCases ¶
type FailureCases[R any] struct { NeedMoreData func() R InvalidOpcode func(opcode byte) R ReservedBits func(bits byte) R WrongMask func(expectMasked bool) R NonCanonicalLength func() R ControlFragmented func() R ControlTooLarge func() R UnexpectedContinuation func() R ExpectedContinuation func() R InvalidUTF8 func() R InvalidClosePayload func() R InvalidCloseCode func(code CloseCode) R MessageTooLarge func(limit int64) R HandshakeRejected func(status int, reason string) R TransportFailed func(err error) R }
FailureCases selects one handler per Failure variant for FailureFold.
type FailureEqOverrides ¶
type FailureEqOverrides struct {
NeedMoreData func(x, y NeedMoreData) (eq, handled bool)
InvalidOpcode func(x, y InvalidOpcode) (eq, handled bool)
ReservedBits func(x, y ReservedBits) (eq, handled bool)
WrongMask func(x, y WrongMask) (eq, handled bool)
NonCanonicalLength func(x, y NonCanonicalLength) (eq, handled bool)
ControlFragmented func(x, y ControlFragmented) (eq, handled bool)
ControlTooLarge func(x, y ControlTooLarge) (eq, handled bool)
UnexpectedContinuation func(x, y UnexpectedContinuation) (eq, handled bool)
ExpectedContinuation func(x, y ExpectedContinuation) (eq, handled bool)
InvalidUTF8 func(x, y InvalidUTF8) (eq, handled bool)
InvalidClosePayload func(x, y InvalidClosePayload) (eq, handled bool)
InvalidCloseCode func(x, y InvalidCloseCode) (eq, handled bool)
MessageTooLarge func(x, y MessageTooLarge) (eq, handled bool)
HandshakeRejected func(x, y HandshakeRejected) (eq, handled bool)
TransportFailed func(x, y TransportFailed) (eq, handled bool)
}
FailureEqOverrides carries optional per-variant hooks for FailureEqualWith. A hook returning handled=false falls through to the derived comparison.
type HTTP2Mode ¶ added in v0.19.0
type HTTP2Mode uint8
HTTP2Mode controls selection of the opening-handshake transport.
const ( // HTTP2Auto prefers RFC 8441 for secure WebSockets and falls back to RFC // 6455 when the peer does not support extended CONNECT. Cleartext ws uses // RFC 6455 unless a custom HTTP2Transport is supplied. HTTP2Auto HTTP2Mode = iota // HTTP1Only disables RFC 8441 and always uses the RFC 6455 Upgrade. HTTP1Only // HTTP2Only requires RFC 8441, including h2c prior knowledge for ws URLs. HTTP2Only )
type HandshakeProtocol ¶ added in v0.19.0
type HandshakeProtocol uint8
HandshakeProtocol identifies how a WebSocket connection was bootstrapped.
const ( RFC6455Handshake HandshakeProtocol = iota RFC8441Handshake RFC9220Handshake )
func (HandshakeProtocol) String ¶ added in v0.19.0
func (p HandshakeProtocol) String() string
type HandshakeRejected ¶
type Header ¶
type Header struct {
Length int64
Mask [4]byte
Opcode Opcode
FIN bool
RSV1 bool
RSV2 bool
RSV3 bool
Masked bool
}
Header is the RFC 6455 frame header. Length is limited to 63 bits.
type InvalidCloseCode ¶
type InvalidCloseCode struct {
Code CloseCode
}
type InvalidClosePayload ¶
type InvalidClosePayload struct{}
type InvalidOpcode ¶
type InvalidOpcode struct {
Opcode byte
}
type InvalidUTF8 ¶
type InvalidUTF8 struct{}
type Lin ¶ added in v0.18.1
type Lin[T any] struct { // contains filtered or unexported fields }
Lin carries a linear (use-exactly-once) value across the erased boundary; Use panics on reuse.
type Message ¶
type Message interface {
// contains filtered or unexported methods
}
Message is the complete application/control message vocabulary.
type MessageTooLarge ¶
type MessageTooLarge struct {
Limit int64
}
type NeedMoreData ¶
type NeedMoreData struct{}
type NonCanonicalLength ¶
type NonCanonicalLength struct{}
type OpenCapability ¶ added in v0.18.1
type OpenCapability struct {
Conn *Conn
}
type OpenSession ¶
type OpenSession struct{}
type Phase ¶
type Phase interface {
// contains filtered or unexported methods
}
Phase indexes the protocol transitions that are valid for a connection.
type PhaseCases ¶
type PhaseCases[R any] struct { ConnectingPhase func() R OpenPhase func() R CloseSentPhase func() R CloseReceivedPhase func() R ClosedPhase func() R }
PhaseCases selects one handler per Phase variant for PhaseFold.
type PhaseEqOverrides ¶
type PhaseEqOverrides struct {
ConnectingPhase func(x, y ConnectingPhase) (eq, handled bool)
OpenPhase func(x, y OpenPhase) (eq, handled bool)
CloseSentPhase func(x, y CloseSentPhase) (eq, handled bool)
CloseReceivedPhase func(x, y CloseReceivedPhase) (eq, handled bool)
ClosedPhase func(x, y ClosedPhase) (eq, handled bool)
}
PhaseEqOverrides carries optional per-variant hooks for PhaseEqualWith. A hook returning handled=false falls through to the derived comparison.
type PingMessage ¶
type PingMessage struct {
Payload []byte
}
type PongMessage ¶
type PongMessage struct {
Payload []byte
}
type ReservedBits ¶
type ReservedBits struct {
Bits byte
}
type Session ¶
type Session interface {
// contains filtered or unexported methods
}
Session is the lightweight proof-token API retained for v0.18 compatibility. New Go+ orchestration should prefer Capability, which also carries linear connection ownership.
func FinishReceived ¶
func FinishSent ¶
func ReceivedClose ¶
type TextMessage ¶
type TextMessage struct {
Payload []byte
}
type TransportFailed ¶
type TransportFailed struct {
Err error
}
type UnexpectedContinuation ¶
type UnexpectedContinuation struct{}
type UpgradeOptions ¶
type UpgradeOptions struct {
Protocols []string
CheckOrigin func(*http.Request) bool
Config ConnConfig
Compression *CompressionOptions
}
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
autobahn
|
|
|
verify
command
|
|
|
cmd
|
|
|
autobahn-client
command
Command autobahn-client runs this implementation against an Autobahn fuzzingserver instance.
|
Command autobahn-client runs this implementation against an Autobahn fuzzingserver instance. |
|
autobahn-server
command
|
|
|
benchgate
command
Command benchgate executes the comparative performance contract.
|
Command benchgate executes the comparative performance contract. |
|
covergate
command
|