Documentation
¶
Overview ¶
Package websocket provides a low-level, zero-dependency WebSocket implementation following RFC 6455. It is used internally by Aero but can also be imported directly for custom WebSocket handling.
Index ¶
- Constants
- Variables
- func Mask(key [4]byte, b []byte)
- func PutCloseFrameBody(p []byte, code CloseStatusCode, reason string)
- func ReadHeader(r *bufio.Reader, dst *Header) error
- func RsvBits(rsv byte) (r1, r2, r3 bool)
- func WriteFrame(w *bufio.Writer, f Frame) error
- func WriteHeader(w *bufio.Writer, h Header) error
- type CloseError
- type CloseStatusCode
- type Conn
- type Frame
- type Handshake
- type Header
- type OpCode
- type Upgrader
Constants ¶
const ( MaxHeaderSize = 14 MinHeaderSize = 2 MaxFrameLength = 1<<63 - 1 )
Variables ¶
var ( ErrBadMethod = errors.New("websocket: request method must be GET") ErrBadProtocol = errors.New("websocket: HTTP version must be at least 1.1") ErrBadHost = errors.New("websocket: missing Host header") ErrBadUpgrade = errors.New("websocket: missing or invalid Upgrade header") ErrBadConnection = errors.New("websocket: missing or invalid Connection header") ErrBadSecKey = errors.New("websocket: missing or invalid Sec-WebSocket-Key") ErrBadSecVersion = errors.New("websocket: missing Sec-WebSocket-Version") ErrHeaderLengthUnexpected = errors.New("websocket: header length is too large") ErrConnClosed = errors.New("websocket: connection closed") ErrFrameTooLarge = errors.New("websocket: frame too large") ErrBadHandshake = errors.New("websocket: bad handshake") ErrNotWebSocket = errors.New("websocket: request is not a websocket upgrade") ErrBadWebSocketKey = errors.New("websocket: missing or invalid Sec-WebSocket-Key") ErrBadWebSocketVersion = errors.New("websocket: client must use version 13") ErrBadWebSocketKeyLen = errors.New("websocket: invalid Sec-WebSocket-Key length") ErrForbiddenOrigin = errors.New("websocket: origin not allowed") ErrHijackNotSupport = errors.New("websocket: response does not support hijacking") ErrUpgradeRequired = errors.New("websocket: unsupported Sec-WebSocket-Version, only 13 is supported") )
Functions ¶
func Mask ¶
Mask applies the WebSocket masking algorithm in-place on b using the 4-byte key. It processes 8 bytes at a time via unsafe uint64 XOR for maximum throughput, falling back to byte-by-byte for the remainder. Masking and unmasking use the same operation, so calling Mask twice restores the original data.
func PutCloseFrameBody ¶
func PutCloseFrameBody(p []byte, code CloseStatusCode, reason string)
PutCloseFrameBody encodes the given status code and reason string into p following the RFC 6455 close frame body layout. p must be at least 2 + len(reason) bytes.
func ReadHeader ¶
ReadHeader reads and parses a WebSocket frame header from r into dst. Returns an error if the stream is malformed or the connection is closed.
func WriteFrame ¶
WriteFrame encodes and writes a complete WebSocket frame to w.
Types ¶
type CloseError ¶
CloseError is returned when the remote peer sends a close frame. It carries the status code and optional reason string.
func NewCloseError ¶
func NewCloseError(code CloseStatusCode, reason string) *CloseError
NewCloseError creates a CloseError with the given status code and reason.
func (*CloseError) Error ¶
func (e *CloseError) Error() string
Error implements the error interface, returning a human-readable description of the close event.
type CloseStatusCode ¶ added in v0.8.5
type CloseStatusCode uint16
CloseStatusCode represents a WebSocket close status code as defined in RFC 6455 §7.4.
const ( CloseNormalClosure CloseStatusCode = 1000 CloseGoingAway CloseStatusCode = 1001 CloseProtocolError CloseStatusCode = 1002 CloseUnsupportedData CloseStatusCode = 1003 CloseNoStatusReceived CloseStatusCode = 1005 CloseAbnormalClosure CloseStatusCode = 1006 CloseInvalidPayload CloseStatusCode = 1007 ClosePolicyViolation CloseStatusCode = 1008 CloseMessageTooBig CloseStatusCode = 1009 CloseMandatoryExtension CloseStatusCode = 1010 CloseInternalServerErr CloseStatusCode = 1011 CloseServiceRestart CloseStatusCode = 1012 CloseTryAgainLater CloseStatusCode = 1013 CloseTLSHandshake CloseStatusCode = 1015 )
func ParseCloseFrameData ¶
func ParseCloseFrameData(payload []byte) (code CloseStatusCode, reason string)
ParseCloseFrameData decodes the status code and reason string from a close frame payload. Returns CloseNormalClosure with an empty reason if the payload is empty.
func ParseCloseFrameDataUnsafe ¶
func ParseCloseFrameDataUnsafe(payload []byte) (code CloseStatusCode, reason string)
ParseCloseFrameDataUnsafe is identical to ParseCloseFrameData but avoids a heap allocation by returning the reason as a string backed by the original payload slice. The caller must not retain the payload after the returned string is used.
func (CloseStatusCode) Value ¶ added in v0.8.5
func (s CloseStatusCode) Value() uint16
Value returns the numeric uint16 representation of the status code, suitable for writing into a close frame payload.
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
Conn is a WebSocket connection over a raw net.Conn. It provides frame-level read/write primitives. For a higher-level API, use [aero.WSConn] via [aero.WebSocket].
func NewConn ¶
NewConn wraps an established net.Conn with buffered reader and writer into a WebSocket Conn ready for frame exchange.
func (*Conn) CloseWithError ¶
func (c *Conn) CloseWithError(code CloseStatusCode, reason string) error
CloseWithError sends a close frame with the given status code and reason before closing the underlying connection.
func (*Conn) NextHeader ¶
NextHeader reads and returns the next frame header from the connection into hdr. Must be called before Conn.ReadPayload for each frame. Returns an error if the connection is closed or the frame is malformed.
func (*Conn) ReadPayload ¶
ReadPayload reads the payload of the frame described by hdr into dst. dst must be pre-allocated to at least hdr.Length bytes. Unmasking is applied automatically if the frame is masked.
type Frame ¶
Frame is a complete WebSocket frame ready to be written to the wire.
func NewBinaryFrame ¶
NewBinaryFrame constructs a FIN binary frame with the given payload.
func NewCloseFrame ¶
NewCloseFrame constructs a close frame with a raw pre-encoded payload. Prefer NewCloseFrameWithReason when constructing close frames manually.
func NewCloseFrameWithReason ¶
func NewCloseFrameWithReason(code CloseStatusCode, reason string) Frame
NewCloseFrameWithReason constructs a close frame with the given status code and reason string encoded into the payload per RFC 6455 §5.5.1.
func NewPingFrame ¶
NewPingFrame constructs a ping control frame with an optional payload (max 125 bytes).
func NewPongFrame ¶
NewPongFrame constructs a pong control frame with an optional payload (max 125 bytes).
func NewTextFrame ¶
NewTextFrame constructs a FIN text frame with the given UTF-8 payload.
type Header ¶
type Header struct {
Fin bool // FIN bit - true if this is the final fragment.
Rsv byte // RSV1-RSV3 bits packed into the low 3 bits.
OpCode OpCode // Frame opcode.
Masked bool // Whether the payload is masked.
Mask [4]byte // Masking key (only meaningful when Masked is true).
Length uint64 // Payload length in bytes.
}
Header represents a parsed WebSocket frame header.
type OpCode ¶
type OpCode byte
OpCode represents a WebSocket frame opcode as defined in RFC 6455 §5.2.
func (OpCode) IsReserved ¶
IsReserved reports whether op is a reserved opcode not defined by RFC 6455.
type Upgrader ¶
type Upgrader struct {
// CheckOrigin validates the Origin header of the upgrade request.
// Return false to reject the handshake with 403 Forbidden.
// If nil, all origins are accepted.
CheckOrigin func(origin string) bool
// Subprotocols lists the server's supported WebSocket subprotocols.
// The best match with the client's Sec-WebSocket-Protocol header is
// selected and echoed in the 101 response.
Subprotocols []string
// WriteTimeout sets the deadline for writing the handshake response.
// A zero value means no timeout.
WriteTimeout time.Duration
}
Upgrader performs the WebSocket HTTP handshake and upgrades the connection.