Documentation
¶
Index ¶
- Variables
- func FormatCloseMessage(code CloseCode, text string) []byte
- func IsCloseError(err error, codes ...CloseCode) bool
- func IsSameOrigin(r *http.Request) bool
- func IsUnexpectedCloseError(err error, expectedCodes ...CloseCode) bool
- func IsWebSocketUpgrade(r *http.Request) bool
- func JoinMessages(c *Conn, term string) io.Reader
- func Subprotocols(r *http.Request) []string
- type BufferPool
- type CloseCode
- type CloseError
- type CloseHandler
- type Compressor
- type Config
- type Conn
- func (c *Conn) Close(code CloseCode, reason string) error
- func (c *Conn) CloseHandler() CloseHandler
- func (c *Conn) EnableSendQueue(size int)
- func (c *Conn) EnableWriteCompression(enable bool)
- func (c *Conn) LocalAddr() net.Addr
- func (c *Conn) NetConn() net.Conn
- func (c *Conn) NextReader() (MessageType, io.Reader, error)
- func (c *Conn) NextWriter(mt MessageType) (io.WriteCloser, error)
- func (c *Conn) PingHandler() PingHandler
- func (c *Conn) PongHandler() PongHandler
- func (c *Conn) Read(ctx context.Context) (MessageType, []byte, error)
- func (c *Conn) ReadJSON(ctx context.Context, v any) error
- func (c *Conn) ReadMessage() (MessageType, []byte, error)
- func (c *Conn) RemoteAddr() net.Addr
- func (c *Conn) Send(ctx context.Context, mt MessageType, data []byte) error
- func (c *Conn) SetCloseHandler(h CloseHandler)
- func (c *Conn) SetCompressionLevel(level int) error
- func (c *Conn) SetPingHandler(h PingHandler)
- func (c *Conn) SetPongHandler(h PongHandler)
- func (c *Conn) SetReadDeadline(t time.Time) error
- func (c *Conn) SetReadLimit(limit int64)
- func (c *Conn) SetWriteDeadline(t time.Time) error
- func (c *Conn) Subprotocol() string
- func (c *Conn) UnderlyingConn() net.Conn
- func (c *Conn) Write(ctx context.Context, mt MessageType, data []byte) error
- func (c *Conn) WriteControl(mt MessageType, payload []byte, deadline time.Time) error
- func (c *Conn) WriteJSON(ctx context.Context, v any) error
- func (c *Conn) WriteMessage(mt MessageType, data []byte) error
- func (c *Conn) WritePreparedMessage(pm *PreparedMessage) error
- type Deflate
- type Dialer
- type Hub
- type Logger
- type MessageType
- type NopLogger
- type PingHandler
- type PongHandler
- type PreparedMessage
- type Upgrader
Constants ¶
This section is empty.
Variables ¶
var ( ErrBadHandshake = errors.New("zsocket: bad handshake") ErrCloseSent = errors.New("zsocket: close sent") ErrReadLimit = errors.New("zsocket: read limit exceeded") )
var ( ErrBadRequest = errors.New("zsocket: bad websocket upgrade request") ErrHandshakeFailed = errors.New("zsocket: handshake failed") ErrOriginNotAllowed = errors.New("zsocket: origin not allowed") ErrSubprotocolRejected = errors.New("zsocket: subprotocol rejected") ErrClosed = errors.New("zsocket: connection closed") ErrTimeout = errors.New("zsocket: timeout") )
var DefaultDialer = &Dialer{ Proxy: http.ProxyFromEnvironment, HandshakeTimeout: 45 * time.Second, ReadBufferSize: 4096, WriteBufferSize: 4096, }
DefaultDialer is the default WebSocket dialer.
var DefaultUpgrader = Upgrader{Config: DefaultConfig()}
DefaultUpgrader uses DefaultConfig values.
Functions ¶
func FormatCloseMessage ¶ added in v1.0.1
FormatCloseMessage formats close payload bytes from code and text.
func IsCloseError ¶ added in v1.0.1
IsCloseError checks whether err is a CloseError with one of the given codes.
func IsSameOrigin ¶ added in v1.0.1
IsSameOrigin returns true if request Origin header matches request Host header.
func IsUnexpectedCloseError ¶ added in v1.0.1
IsUnexpectedCloseError reports whether err is a CloseError that is not expected.
func IsWebSocketUpgrade ¶ added in v1.0.1
IsWebSocketUpgrade reports whether an HTTP request asks for websocket upgrade.
func JoinMessages ¶ added in v1.0.1
JoinMessages returns a reader that joins text or binary messages with term.
func Subprotocols ¶ added in v1.0.1
Subprotocols returns the client requested subprotocol list.
Types ¶
type BufferPool ¶ added in v1.0.1
BufferPool is a generic reusable buffer pool.
func NewBufferPool ¶ added in v1.0.1
func NewBufferPool(size int) BufferPool
NewBufferPool creates a sync.Pool-backed byte buffer pool.
type CloseCode ¶
type CloseCode uint16
CloseCode follows RFC 6455 close codes (select common ones here).
const ( CloseNormalClosure CloseCode = 1000 CloseGoingAway CloseCode = 1001 CloseProtocolError CloseCode = 1002 CloseUnsupportedData CloseCode = 1003 CloseNoStatusRcvd CloseCode = 1005 // reserved - do not send CloseNoStatusReceived CloseCode = CloseNoStatusRcvd CloseAbnormalClosure CloseCode = 1006 // reserved - do not send CloseInvalidFramePayloadData CloseCode = 1007 ClosePolicyViolation CloseCode = 1008 CloseMessageTooBig CloseCode = 1009 CloseMandatoryExtension CloseCode = 1010 CloseInternalServerErr CloseCode = 1011 CloseTLSHandshake CloseCode = 1015 )
type CloseError ¶
CloseError is returned when a close frame is received or needs to be sent.
func (CloseError) Error ¶
func (e CloseError) Error() string
type CloseHandler ¶ added in v1.0.1
CloseHandler handles incoming close control frames.
type Compressor ¶ added in v1.0.1
type Compressor interface {
Compress(data []byte) ([]byte, error)
Decompress(data []byte) ([]byte, error)
}
Compressor describes per-message compression behavior.
type Config ¶
type Config struct {
// AllowedOrigins is used to check request Origin. Empty means "allow all".
AllowedOrigins []string
// Subprotocols contains allowed subprotocol names.
Subprotocols []string
// HandshakeTimeout controls the HTTP upgrade deadline.
HandshakeTimeout time.Duration
// ReadLimit caps the maximum message payload (bytes). 0 means no limit.
ReadLimit int64
// ReadBufferSize / WriteBufferSize are used for buffered I/O.
ReadBufferSize int
WriteBufferSize int
// PingInterval sets how often to send pings. 0 disables keepalive pings.
PingInterval time.Duration
// PongWait is how long to wait for a pong after a ping. Must be > 0 if PingInterval > 0.
PongWait time.Duration
// WriteTimeout caps write operations (frames & control frames).
WriteTimeout time.Duration
// CheckOrigin allows custom origin validation. If set, overrides AllowedOrigins.
CheckOrigin func(r *http.Request) bool
// Logger is optional. If nil, logging is no-op.
Logger Logger
// EnableCompression enables per-message deflate negotiation.
EnableCompression bool
// CompressionLevel controls flate level when compression is enabled.
CompressionLevel int
// WriteBufferPool optionally provides reusable write buffers.
WriteBufferPool BufferPool
}
Config controls WebSocket server behavior during handshake and runtime.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns a practical default config for servers.
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
Conn is a server-side WebSocket connection managed by zsocket. It exposes Read/Write methods, JSON helpers, and graceful Close. Concurrency: one reader goroutine internally; writes are serialized via writeMu.
NOTE: This MVP supports basic fragmentation (accumulate until FIN). Extensions are not implemented.
func Accept ¶
Accept upgrades an HTTP request to a WebSocket connection and returns a *Conn. It does a minimal RFC6455 handshake with origin & subprotocol checks, then hijacks the underlying TCP connection for frame I/O.
func (*Conn) CloseHandler ¶ added in v1.0.1
func (c *Conn) CloseHandler() CloseHandler
CloseHandler returns the current close handler.
func (*Conn) EnableSendQueue ¶ added in v1.0.1
EnableSendQueue configures async write queue with backpressure.
func (*Conn) EnableWriteCompression ¶ added in v1.0.1
EnableWriteCompression enables or disables write-side compression.
func (*Conn) NextReader ¶ added in v1.0.1
func (c *Conn) NextReader() (MessageType, io.Reader, error)
NextReader returns the next complete message payload as an io.Reader.
func (*Conn) NextWriter ¶ added in v1.0.1
func (c *Conn) NextWriter(mt MessageType) (io.WriteCloser, error)
NextWriter returns a writer for the next message.
func (*Conn) PingHandler ¶ added in v1.0.1
func (c *Conn) PingHandler() PingHandler
PingHandler returns the current ping handler.
func (*Conn) PongHandler ¶ added in v1.0.1
func (c *Conn) PongHandler() PongHandler
PongHandler returns the current pong handler.
func (*Conn) Read ¶
Read reads the next complete message, returning its type and payload. It accumulates fragments until FIN=1. Control frames are handled internally.
func (*Conn) ReadJSON ¶
ReadJSON reads next message and unmarshals JSON into v. It accepts both text and binary frames. If binary, it still tries to decode JSON.
func (*Conn) ReadMessage ¶ added in v1.0.1
func (c *Conn) ReadMessage() (MessageType, []byte, error)
ReadMessage reads next data message.
func (*Conn) RemoteAddr ¶
RemoteAddr returns the peer network address.
func (*Conn) Send ¶ added in v1.0.1
Send enqueues a message if queue enabled, otherwise writes directly.
func (*Conn) SetCloseHandler ¶ added in v1.0.1
func (c *Conn) SetCloseHandler(h CloseHandler)
SetCloseHandler sets a custom close handler. Nil resets the default behavior.
func (*Conn) SetCompressionLevel ¶ added in v1.0.1
SetCompressionLevel changes the compression level for future messages.
func (*Conn) SetPingHandler ¶ added in v1.0.1
func (c *Conn) SetPingHandler(h PingHandler)
SetPingHandler sets a custom ping handler. Nil resets the default behavior.
func (*Conn) SetPongHandler ¶ added in v1.0.1
func (c *Conn) SetPongHandler(h PongHandler)
SetPongHandler sets a custom pong handler. Nil resets the default behavior.
func (*Conn) SetReadDeadline ¶ added in v1.0.1
SetReadDeadline sets the deadline for future reads.
func (*Conn) SetReadLimit ¶ added in v1.0.1
SetReadLimit sets the maximum message payload size in bytes. 0 means unlimited.
func (*Conn) SetWriteDeadline ¶ added in v1.0.1
SetWriteDeadline sets the deadline for future writes.
func (*Conn) Subprotocol ¶
Subprotocol returns the negotiated subprotocol, if any.
func (*Conn) UnderlyingConn ¶ added in v1.0.1
UnderlyingConn is an alias for NetConn.
func (*Conn) Write ¶
Write sends a complete message (text or binary) as a single unfragmented frame.
func (*Conn) WriteControl ¶
WriteControl writes a control frame using message type and deadline.
func (*Conn) WriteMessage ¶ added in v1.0.1
func (c *Conn) WriteMessage(mt MessageType, data []byte) error
WriteMessage writes one data message.
func (*Conn) WritePreparedMessage ¶ added in v1.0.1
func (c *Conn) WritePreparedMessage(pm *PreparedMessage) error
WritePreparedMessage writes a prebuilt message efficiently.
type Deflate ¶ added in v1.0.1
type Deflate struct {
// contains filtered or unexported fields
}
Deflate implements RFC7692 per-message deflate.
func NewDeflate ¶ added in v1.0.1
NewDeflate creates a deflate compressor with the given level.
type Dialer ¶ added in v1.0.1
type Dialer struct {
NetDial func(network, addr string) (net.Conn, error)
NetDialContext func(ctx context.Context, network, addr string) (net.Conn, error)
NetDialTLSContext func(ctx context.Context, network, addr string) (net.Conn, error)
Proxy func(*http.Request) (*url.URL, error)
TLSClientConfig *tls.Config
HandshakeTimeout time.Duration
Subprotocols []string
ReadBufferSize int
WriteBufferSize int
EnableCompression bool
Jar http.CookieJar
}
Dialer configures WebSocket client connections.
type Hub ¶
type Hub struct {
// contains filtered or unexported fields
}
Hub manages subscriptions (rooms) and broadcasts messages to members. It is safe for concurrent use.
NOTE: Basic single-process hub. For horizontal scale, back it with Redis pub/sub or another broker.
func (*Hub) BroadcastNonBlocking ¶ added in v1.0.1
func (h *Hub) BroadcastNonBlocking(room string, mt MessageType, msg []byte)
BroadcastNonBlocking sends with short per-connection timeout.
type MessageType ¶
type MessageType byte
MessageType represents the WebSocket message type.
const ( TextMessage MessageType = 1 BinaryMessage MessageType = 2 CloseMessage MessageType = 8 PingMessage MessageType = 9 PongMessage MessageType = 10 )
type PingHandler ¶ added in v1.0.1
PingHandler handles incoming ping control frames.
type PongHandler ¶ added in v1.0.1
PongHandler handles incoming pong control frames.
type PreparedMessage ¶ added in v1.0.1
type PreparedMessage struct {
// contains filtered or unexported fields
}
PreparedMessage stores message data for repeated writes.
func NewPreparedMessage ¶ added in v1.0.1
func NewPreparedMessage(mt MessageType, data []byte) (*PreparedMessage, error)
NewPreparedMessage creates a prepared message for repeated sending.