Documentation
¶
Overview ¶
websocket/errors.go
websocket/hub.go
websocket/message.go
websocket/websocket.go
Index ¶
- Variables
- func Handler(opts *AcceptOptions, handler func(*Conn)) http.Handler
- func HandlerFunc(opts *AcceptOptions, handler func(*Conn)) http.HandlerFunc
- func IsCloseError(err error) bool
- func IsNormalClose(err error) bool
- func RunWithConfig(ctx context.Context, conn *Conn, cfg Config, ...) error
- type AcceptOptions
- type Client
- func (c *Client) Close() error
- func (c *Client) Conn() *Conn
- func (c *Client) Get(key string) (any, bool)
- func (c *Client) GetString(key string) string
- func (c *Client) ID() string
- func (c *Client) InRoom(roomName string) bool
- func (c *Client) Join(roomName string)
- func (c *Client) Leave(roomName string)
- func (c *Client) Rooms() []string
- func (c *Client) Send(ctx context.Context, msgType MessageType, data []byte) error
- func (c *Client) SendBinary(ctx context.Context, data []byte) error
- func (c *Client) SendEvent(ctx context.Context, name string, data any) error
- func (c *Client) SendJSON(ctx context.Context, v any) error
- func (c *Client) SendMessage(ctx context.Context, msg *Message) error
- func (c *Client) SendText(ctx context.Context, msg string) error
- func (c *Client) SendTypedMessage(ctx context.Context, msgType string, payload any) error
- func (c *Client) Set(key string, value any)
- type CloseError
- type CompressionMode
- type Config
- type Conn
- func (c *Conn) Close() error
- func (c *Conn) CloseWithReason(code StatusCode, reason string) error
- func (c *Conn) IsClosed() bool
- func (c *Conn) Ping(ctx context.Context) error
- func (c *Conn) Read(ctx context.Context) (MessageType, []byte, error)
- func (c *Conn) ReadBinary(ctx context.Context) ([]byte, error)
- func (c *Conn) ReadJSON(ctx context.Context, v any) error
- func (c *Conn) ReadMessage(ctx context.Context) (*Message, error)
- func (c *Conn) ReadText(ctx context.Context) (string, error)
- func (c *Conn) SetReadLimit(limit int64)
- func (c *Conn) Subprotocol() string
- func (c *Conn) Write(ctx context.Context, msgType MessageType, data []byte) error
- func (c *Conn) WriteBinary(ctx context.Context, data []byte) error
- func (c *Conn) WriteJSON(ctx context.Context, v any) error
- func (c *Conn) WriteMessage(ctx context.Context, msg *Message) error
- func (c *Conn) WriteText(ctx context.Context, msg string) error
- type Event
- type Hub
- func (h *Hub) Broadcast(ctx context.Context, msgType MessageType, data []byte) error
- func (h *Hub) BroadcastBinary(ctx context.Context, data []byte) error
- func (h *Hub) BroadcastEvent(ctx context.Context, name string, data any) error
- func (h *Hub) BroadcastExcept(ctx context.Context, except *Client, msgType MessageType, data []byte) error
- func (h *Hub) BroadcastJSON(ctx context.Context, v any) error
- func (h *Hub) BroadcastMessage(ctx context.Context, msg *Message) error
- func (h *Hub) BroadcastText(ctx context.Context, msg string) error
- func (h *Hub) BroadcastTypedMessage(ctx context.Context, msgType string, payload any) error
- func (h *Hub) Clients() int
- func (h *Hub) Close()
- func (h *Hub) DeleteRoom(name string)
- func (h *Hub) ForEach(fn func(*Client))
- func (h *Hub) GetRoom(name string) *Room
- func (h *Hub) NewClient(conn *Conn, id string) *Client
- func (h *Hub) Room(name string) *Room
- func (h *Hub) Rooms() []string
- type Message
- type MessageHandler
- type MessageType
- type Room
- func (r *Room) Broadcast(ctx context.Context, msgType MessageType, data []byte) error
- func (r *Room) BroadcastEvent(ctx context.Context, name string, data any) error
- func (r *Room) BroadcastExcept(ctx context.Context, except *Client, msgType MessageType, data []byte) error
- func (r *Room) BroadcastJSON(ctx context.Context, v any) error
- func (r *Room) BroadcastMessage(ctx context.Context, msg *Message) error
- func (r *Room) BroadcastText(ctx context.Context, msg string) error
- func (r *Room) BroadcastTypedMessage(ctx context.Context, msgType string, payload any) error
- func (r *Room) ForEach(fn func(*Client))
- func (r *Room) Has(client *Client) bool
- func (r *Room) Join(client *Client)
- func (r *Room) Leave(client *Client)
- func (r *Room) Name() string
- func (r *Room) Size() int
- type Router
- func (r *Router) Default(handler MessageHandler)
- func (r *Router) Handle(msgType string, handler MessageHandler)
- func (r *Router) HandleRaw(ctx context.Context, client *Client, data []byte) error
- func (r *Router) Route(ctx context.Context, client *Client, msg *Message) error
- func (r *Router) RunClient(ctx context.Context, client *Client) error
- type StatusCode
Constants ¶
This section is empty.
Variables ¶
var ( // ErrConnectionClosed is returned when attempting to write to a closed connection. ErrConnectionClosed = errors.New("websocket: connection closed") // ErrExpectedTextMessage is returned when a text message was expected but not received. ErrExpectedTextMessage = errors.New("websocket: expected text message") // ErrExpectedBinaryMessage is returned when a binary message was expected but not received. ErrExpectedBinaryMessage = errors.New("websocket: expected binary message") // ErrHubClosed is returned when attempting to use a closed hub. ErrHubClosed = errors.New("websocket: hub closed") // ErrRoomNotFound is returned when a room does not exist. ErrRoomNotFound = errors.New("websocket: room not found") // ErrClientNotFound is returned when a client is not registered. ErrClientNotFound = errors.New("websocket: client not found") // ErrInvalidMessageType is returned for unsupported message types. ErrInvalidMessageType = errors.New("websocket: invalid message type") )
Common WebSocket errors.
Functions ¶
func Handler ¶
func Handler(opts *AcceptOptions, handler func(*Conn)) http.Handler
Handler creates an http.Handler that upgrades connections and calls the handler.
func HandlerFunc ¶
func HandlerFunc(opts *AcceptOptions, handler func(*Conn)) http.HandlerFunc
HandlerFunc creates an http.HandlerFunc that upgrades connections.
func IsCloseError ¶
IsCloseError returns true if the error is a WebSocket close error.
func IsNormalClose ¶
IsNormalClose returns true if the error is a normal close.
Types ¶
type AcceptOptions ¶
type AcceptOptions struct {
// Subprotocols lists the server's supported subprotocols.
// The first match with a client-requested subprotocol is selected.
Subprotocols []string
// InsecureSkipVerify disables origin verification.
// Only use for development/testing.
InsecureSkipVerify bool
// OriginPatterns specifies allowed origin patterns.
// Use "*" for any origin (not recommended for production).
// Example: []string{"https://example.com", "https://*.example.com"}
OriginPatterns []string
// CompressionMode controls message compression.
// Defaults to CompressionDisabled.
CompressionMode CompressionMode
// CompressionThreshold is the minimum message size to compress.
// Messages smaller than this are sent uncompressed.
// Defaults to 512 bytes.
CompressionThreshold int
}
AcceptOptions configures the WebSocket upgrade.
func DefaultAcceptOptions ¶
func DefaultAcceptOptions() AcceptOptions
DefaultAcceptOptions returns sensible defaults for accepting connections.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client represents a connected WebSocket client.
func (*Client) SendBinary ¶
SendBinary sends a binary message to the client.
func (*Client) SendMessage ¶
SendMessage sends a structured Message to the client.
func (*Client) SendTypedMessage ¶
SendTypedMessage creates and sends a message with the given type and payload.
type CloseError ¶
type CloseError struct {
Code StatusCode
Reason string
}
CloseError represents a WebSocket close error.
func (*CloseError) Error ¶
func (e *CloseError) Error() string
Error implements the error interface.
type CompressionMode ¶
type CompressionMode int
CompressionMode specifies the compression mode for messages.
const ( // CompressionDisabled disables compression. CompressionDisabled CompressionMode = iota // CompressionContextTakeover enables compression with context takeover. // More efficient but uses more memory per connection. CompressionContextTakeover // CompressionNoContextTakeover enables compression without context takeover. // Less memory per connection but slightly less efficient. CompressionNoContextTakeover )
type Config ¶
type Config struct {
// ReadTimeout is the maximum time to wait for a message.
// Zero means no timeout.
ReadTimeout time.Duration
// WriteTimeout is the maximum time to wait when writing a message.
// Zero means no timeout.
WriteTimeout time.Duration
// PingInterval is how often to send pings to keep the connection alive.
// Zero disables automatic pings.
PingInterval time.Duration
// PongTimeout is how long to wait for a pong response.
// Defaults to PingInterval if not set.
PongTimeout time.Duration
// MaxMessageSize is the maximum message size to accept.
// Defaults to 32KB.
MaxMessageSize int64
}
Config holds configuration for WebSocket connections.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns sensible defaults for WebSocket configuration.
type Conn ¶
type Conn struct {
// OnClose is called when the connection is closed.
OnClose func()
// contains filtered or unexported fields
}
Conn wraps a WebSocket connection with additional functionality.
func Accept ¶
func Accept(w http.ResponseWriter, r *http.Request, opts *AcceptOptions) (*Conn, error)
Accept upgrades an HTTP connection to a WebSocket connection.
func (*Conn) CloseWithReason ¶
func (c *Conn) CloseWithReason(code StatusCode, reason string) error
CloseWithReason closes the WebSocket connection with a status code and reason.
func (*Conn) Ping ¶
Ping sends a ping to the peer and waits for a pong. This is useful for keeping the connection alive and detecting dead connections.
func (*Conn) Read ¶
Read reads a message from the connection. It blocks until a message is received or the context is canceled.
func (*Conn) ReadBinary ¶
ReadBinary reads a binary message from the connection. Returns an error if the message is not a binary message.
func (*Conn) ReadMessage ¶
ReadMessage reads a structured Message from the connection.
func (*Conn) ReadText ¶
ReadText reads a text message from the connection. Returns an error if the message is not a text message.
func (*Conn) SetReadLimit ¶
SetReadLimit sets the maximum message size that can be read. The default is 32KB.
func (*Conn) Subprotocol ¶
Subprotocol returns the negotiated subprotocol. Returns an empty string if no subprotocol was negotiated.
func (*Conn) WriteBinary ¶
WriteBinary writes a binary message to the connection.
func (*Conn) WriteMessage ¶
WriteMessage writes a structured Message to the connection.
type Hub ¶
type Hub struct {
// OnConnect is called when a client connects.
OnConnect func(*Client)
// OnDisconnect is called when a client disconnects.
OnDisconnect func(*Client)
// contains filtered or unexported fields
}
Hub manages WebSocket connections and enables broadcasting.
func (*Hub) BroadcastBinary ¶
BroadcastBinary sends a binary message to all connected clients.
func (*Hub) BroadcastEvent ¶
BroadcastEvent broadcasts an event to all connected clients.
func (*Hub) BroadcastExcept ¶
func (h *Hub) BroadcastExcept(ctx context.Context, except *Client, msgType MessageType, data []byte) error
BroadcastExcept sends a message to all clients except the specified one.
func (*Hub) BroadcastJSON ¶
BroadcastJSON sends a JSON message to all connected clients.
func (*Hub) BroadcastMessage ¶
BroadcastMessage sends a structured Message to all connected clients.
func (*Hub) BroadcastText ¶
BroadcastText sends a text message to all connected clients.
func (*Hub) BroadcastTypedMessage ¶
BroadcastTypedMessage creates and broadcasts a message with the given type and payload.
func (*Hub) DeleteRoom ¶
DeleteRoom removes a room and removes all clients from it.
type Message ¶
type Message struct {
// Type identifies the message type (e.g., "chat", "notification", "error").
Type string `json:"type"`
// Payload contains the message data.
Payload json.RawMessage `json:"payload,omitempty"`
// ID is an optional message identifier for request/response correlation.
ID string `json:"id,omitempty"`
}
Message represents a structured WebSocket message with a type and payload.
func NewMessage ¶
NewMessage creates a new message with the given type and payload.
func NewMessageWithID ¶
NewMessageWithID creates a new message with type, payload, and ID.
func UnmarshalMessage ¶
UnmarshalMessage parses JSON data into a Message.
func (*Message) ParsePayload ¶
ParsePayload unmarshals the message payload into the provided value.
type MessageHandler ¶
MessageHandler is a function that handles a specific message type.
type MessageType ¶
type MessageType int
MessageType represents the type of WebSocket message.
const ( // MessageText is a text message (UTF-8 encoded). MessageText MessageType = MessageType(websocket.MessageText) // MessageBinary is a binary message. MessageBinary MessageType = MessageType(websocket.MessageBinary) )
type Room ¶
type Room struct {
// contains filtered or unexported fields
}
Room represents a group of clients that can receive broadcasts.
func (*Room) BroadcastEvent ¶
BroadcastEvent broadcasts an event to all clients in the room.
func (*Room) BroadcastExcept ¶
func (r *Room) BroadcastExcept(ctx context.Context, except *Client, msgType MessageType, data []byte) error
BroadcastExcept sends a message to all room clients except the specified one.
func (*Room) BroadcastJSON ¶
BroadcastJSON sends a JSON message to all clients in the room.
func (*Room) BroadcastMessage ¶
BroadcastMessage sends a structured Message to all clients in the room.
func (*Room) BroadcastText ¶
BroadcastText sends a text message to all clients in the room.
func (*Room) BroadcastTypedMessage ¶
BroadcastTypedMessage creates and broadcasts a message with the given type and payload.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router routes messages to handlers based on message type.
func (*Router) Default ¶
func (r *Router) Default(handler MessageHandler)
Default sets the default handler for unregistered message types.
func (*Router) Handle ¶
func (r *Router) Handle(msgType string, handler MessageHandler)
Handle registers a handler for a message type.
type StatusCode ¶
type StatusCode int
StatusCode represents a WebSocket close status code.
const ( StatusNormalClosure StatusCode = StatusCode(websocket.StatusNormalClosure) StatusGoingAway StatusCode = StatusCode(websocket.StatusGoingAway) StatusProtocolError StatusCode = StatusCode(websocket.StatusProtocolError) StatusUnsupportedData StatusCode = StatusCode(websocket.StatusUnsupportedData) StatusNoStatusRcvd StatusCode = StatusCode(websocket.StatusNoStatusRcvd) StatusAbnormalClosure StatusCode = StatusCode(websocket.StatusAbnormalClosure) StatusInvalidPayload StatusCode = StatusCode(websocket.StatusInvalidFramePayloadData) StatusPolicyViolation StatusCode = StatusCode(websocket.StatusPolicyViolation) StatusMessageTooBig StatusCode = StatusCode(websocket.StatusMessageTooBig) StatusMandatoryExt StatusCode = StatusCode(websocket.StatusMandatoryExtension) StatusInternalError StatusCode = StatusCode(websocket.StatusInternalError) StatusServiceRestart StatusCode = StatusCode(websocket.StatusServiceRestart) StatusTryAgainLater StatusCode = StatusCode(websocket.StatusTryAgainLater) StatusBadGateway StatusCode = StatusCode(websocket.StatusBadGateway) )