websocket

package
v0.1.36 Latest Latest
Warning

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

Go to latest
Published: Feb 25, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

websocket/errors.go

websocket/hub.go

websocket/message.go

websocket/websocket.go

Index

Constants

This section is empty.

Variables

View Source
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

func IsCloseError(err error) bool

IsCloseError returns true if the error is a WebSocket close error.

func IsNormalClose

func IsNormalClose(err error) bool

IsNormalClose returns true if the error is a normal close.

func RunWithConfig

func RunWithConfig(ctx context.Context, conn *Conn, cfg Config, handler func(ctx context.Context, msgType MessageType, data []byte) error) error

RunWithConfig runs a connection handler with the given configuration. It handles ping/pong automatically and respects timeouts.

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) Close

func (c *Client) Close() error

Close closes the client's connection.

func (*Client) Conn

func (c *Client) Conn() *Conn

Conn returns the underlying WebSocket connection.

func (*Client) Get

func (c *Client) Get(key string) (any, bool)

Get retrieves a value associated with the client.

func (*Client) GetString

func (c *Client) GetString(key string) string

GetString retrieves a string value associated with the client.

func (*Client) ID

func (c *Client) ID() string

ID returns the client's identifier.

func (*Client) InRoom

func (c *Client) InRoom(roomName string) bool

InRoom returns true if the client is in the specified room.

func (*Client) Join

func (c *Client) Join(roomName string)

Join adds the client to a room.

func (*Client) Leave

func (c *Client) Leave(roomName string)

Leave removes the client from a room.

func (*Client) Rooms

func (c *Client) Rooms() []string

Rooms returns the names of rooms the client is in.

func (*Client) Send

func (c *Client) Send(ctx context.Context, msgType MessageType, data []byte) error

Send sends a message to the client.

func (*Client) SendBinary

func (c *Client) SendBinary(ctx context.Context, data []byte) error

SendBinary sends a binary message to the client.

func (*Client) SendEvent

func (c *Client) SendEvent(ctx context.Context, name string, data any) error

SendEvent sends an event to the client.

func (*Client) SendJSON

func (c *Client) SendJSON(ctx context.Context, v any) error

SendJSON sends a JSON message to the client.

func (*Client) SendMessage

func (c *Client) SendMessage(ctx context.Context, msg *Message) error

SendMessage sends a structured Message to the client.

func (*Client) SendText

func (c *Client) SendText(ctx context.Context, msg string) error

SendText sends a text message to the client.

func (*Client) SendTypedMessage

func (c *Client) SendTypedMessage(ctx context.Context, msgType string, payload any) error

SendTypedMessage creates and sends a message with the given type and payload.

func (*Client) Set

func (c *Client) Set(key string, value any)

Set stores a value associated with the client.

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) Close

func (c *Conn) Close() error

Close closes the WebSocket connection with a normal closure.

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) IsClosed

func (c *Conn) IsClosed() bool

IsClosed returns true if the connection has been closed.

func (*Conn) Ping

func (c *Conn) Ping(ctx context.Context) error

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

func (c *Conn) Read(ctx context.Context) (MessageType, []byte, error)

Read reads a message from the connection. It blocks until a message is received or the context is canceled.

func (*Conn) ReadBinary

func (c *Conn) ReadBinary(ctx context.Context) ([]byte, error)

ReadBinary reads a binary message from the connection. Returns an error if the message is not a binary message.

func (*Conn) ReadJSON

func (c *Conn) ReadJSON(ctx context.Context, v any) error

ReadJSON reads a JSON message from the connection.

func (*Conn) ReadMessage

func (c *Conn) ReadMessage(ctx context.Context) (*Message, error)

ReadMessage reads a structured Message from the connection.

func (*Conn) ReadText

func (c *Conn) ReadText(ctx context.Context) (string, error)

ReadText reads a text message from the connection. Returns an error if the message is not a text message.

func (*Conn) SetReadLimit

func (c *Conn) SetReadLimit(limit int64)

SetReadLimit sets the maximum message size that can be read. The default is 32KB.

func (*Conn) Subprotocol

func (c *Conn) Subprotocol() string

Subprotocol returns the negotiated subprotocol. Returns an empty string if no subprotocol was negotiated.

func (*Conn) Write

func (c *Conn) Write(ctx context.Context, msgType MessageType, data []byte) error

Write writes a message to the connection. It is safe to call concurrently.

func (*Conn) WriteBinary

func (c *Conn) WriteBinary(ctx context.Context, data []byte) error

WriteBinary writes a binary message to the connection.

func (*Conn) WriteJSON

func (c *Conn) WriteJSON(ctx context.Context, v any) error

WriteJSON writes a JSON message to the connection.

func (*Conn) WriteMessage

func (c *Conn) WriteMessage(ctx context.Context, msg *Message) error

WriteMessage writes a structured Message to the connection.

func (*Conn) WriteText

func (c *Conn) WriteText(ctx context.Context, msg string) error

WriteText writes a text message to the connection.

type Event

type Event struct {
	Name string `json:"name"`
	Data any    `json:"data,omitempty"`
}

Event is a simple event message for pub/sub patterns.

func NewEvent

func NewEvent(name string, data any) *Event

NewEvent creates a new event.

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 NewHub

func NewHub() *Hub

NewHub creates a new connection hub.

func (*Hub) Broadcast

func (h *Hub) Broadcast(ctx context.Context, msgType MessageType, data []byte) error

Broadcast sends a message to all connected clients.

func (*Hub) BroadcastBinary

func (h *Hub) BroadcastBinary(ctx context.Context, data []byte) error

BroadcastBinary sends a binary message to all connected clients.

func (*Hub) BroadcastEvent

func (h *Hub) BroadcastEvent(ctx context.Context, name string, data any) error

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

func (h *Hub) BroadcastJSON(ctx context.Context, v any) error

BroadcastJSON sends a JSON message to all connected clients.

func (*Hub) BroadcastMessage

func (h *Hub) BroadcastMessage(ctx context.Context, msg *Message) error

BroadcastMessage sends a structured Message to all connected clients.

func (*Hub) BroadcastText

func (h *Hub) BroadcastText(ctx context.Context, msg string) error

BroadcastText sends a text message to all connected clients.

func (*Hub) BroadcastTypedMessage

func (h *Hub) BroadcastTypedMessage(ctx context.Context, msgType string, payload any) error

BroadcastTypedMessage creates and broadcasts a message with the given type and payload.

func (*Hub) Clients

func (h *Hub) Clients() int

Clients returns the number of connected clients.

func (*Hub) Close

func (h *Hub) Close()

Close closes the hub and all client connections.

func (*Hub) DeleteRoom

func (h *Hub) DeleteRoom(name string)

DeleteRoom removes a room and removes all clients from it.

func (*Hub) ForEach

func (h *Hub) ForEach(fn func(*Client))

ForEach iterates over all connected clients.

func (*Hub) GetRoom

func (h *Hub) GetRoom(name string) *Room

GetRoom returns a room by name, creating it if it doesn't exist.

func (*Hub) NewClient

func (h *Hub) NewClient(conn *Conn, id string) *Client

NewClient creates a new client and registers it with the hub.

func (*Hub) Room

func (h *Hub) Room(name string) *Room

Room returns a room by name, or nil if it doesn't exist.

func (*Hub) Rooms

func (h *Hub) Rooms() []string

Rooms returns the names of all rooms.

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

func NewMessage(msgType string, payload any) (*Message, error)

NewMessage creates a new message with the given type and payload.

func NewMessageWithID

func NewMessageWithID(id, msgType string, payload any) (*Message, error)

NewMessageWithID creates a new message with type, payload, and ID.

func UnmarshalMessage

func UnmarshalMessage(data []byte) (*Message, error)

UnmarshalMessage parses JSON data into a Message.

func (*Message) Marshal

func (m *Message) Marshal() ([]byte, error)

Marshal serializes the message to JSON bytes.

func (*Message) ParsePayload

func (m *Message) ParsePayload(v any) error

ParsePayload unmarshals the message payload into the provided value.

type MessageHandler

type MessageHandler func(ctx context.Context, client *Client, msg *Message) error

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) Broadcast

func (r *Room) Broadcast(ctx context.Context, msgType MessageType, data []byte) error

Broadcast sends a message to all clients in the room.

func (*Room) BroadcastEvent

func (r *Room) BroadcastEvent(ctx context.Context, name string, data any) error

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

func (r *Room) BroadcastJSON(ctx context.Context, v any) error

BroadcastJSON sends a JSON message to all clients in the room.

func (*Room) BroadcastMessage

func (r *Room) BroadcastMessage(ctx context.Context, msg *Message) error

BroadcastMessage sends a structured Message to all clients in the room.

func (*Room) BroadcastText

func (r *Room) BroadcastText(ctx context.Context, msg string) error

BroadcastText sends a text message to all clients in the room.

func (*Room) BroadcastTypedMessage

func (r *Room) BroadcastTypedMessage(ctx context.Context, msgType string, payload any) error

BroadcastTypedMessage creates and broadcasts a message with the given type and payload.

func (*Room) ForEach

func (r *Room) ForEach(fn func(*Client))

ForEach iterates over all clients in the room.

func (*Room) Has

func (r *Room) Has(client *Client) bool

Has returns true if the client is in the room.

func (*Room) Join

func (r *Room) Join(client *Client)

Join adds a client to the room.

func (*Room) Leave

func (r *Room) Leave(client *Client)

Leave removes a client from the room.

func (*Room) Name

func (r *Room) Name() string

Name returns the room name.

func (*Room) Size

func (r *Room) Size() int

Size returns the number of clients in the room.

type Router

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

Router routes messages to handlers based on message type.

func NewRouter

func NewRouter() *Router

NewRouter creates a new message router.

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.

func (*Router) HandleRaw

func (r *Router) HandleRaw(ctx context.Context, client *Client, data []byte) error

HandleRaw handles raw message data by parsing and routing it.

func (*Router) Route

func (r *Router) Route(ctx context.Context, client *Client, msg *Message) error

Route routes a message to the appropriate handler.

func (*Router) RunClient

func (r *Router) RunClient(ctx context.Context, client *Client) error

RunClient runs a message loop for a client using the router.

Jump to

Keyboard shortcuts

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