Documentation
¶
Overview ¶
Package wskit provides a WebSocket hub-and-spoke server built on coder/websocket.
Hub and Client ¶
Create a Hub with NewHub (optionally WithRedis for multi-instance broadcast), run Hub.Run(ctx) in a goroutine, then use Accept to upgrade HTTP connections and register clients. Run Client.ReadPump and Client.WritePump in separate goroutines per connection.
Event envelope ¶
Event and NewEvent provide a standard JSON envelope (type, payload, timestamp). Use Hub.BroadcastEvent or Hub.BroadcastJSON to send to all clients.
Redis Pub/Sub ¶
WithRedis(client, channel) enables publishing to Redis on BroadcastEvent/BroadcastJSON; other instances run SubscribeToRedis(ctx) to receive and broadcast locally.
Options ¶
Hub: WithRedis, WithBroadcastBuf, WithRegisterBuf, WithChannelTimeout, WithOnTimeout, WithOnConnect. Client: WithWriteWait, WithPingInterval, WithMaxMessageSize, WithSendBufSize.
Index ¶
- Constants
- Variables
- type AcceptFunc
- type Client
- type ClientConfig
- type ClientOption
- type Conn
- type Event
- type Hub
- func (h *Hub) Broadcast(data []byte)
- func (h *Hub) BroadcastEvent(ctx context.Context, event any) error
- func (h *Hub) BroadcastJSON(ctx context.Context, typ string, payload any) error
- func (h *Hub) ClientCount() int
- func (h *Hub) Register(client *Client)
- func (h *Hub) Run(ctx context.Context)
- func (h *Hub) SubscribeToRedis(ctx context.Context)
- func (h *Hub) Unregister(client *Client)
- type HubOption
- type OnConnect
Constants ¶
const ( DefaultWriteWait = 10 * time.Second DefaultPingInterval = 30 * time.Second DefaultMaxMessageSize = 512 DefaultSendBufSize = 256 )
const ( DefaultBroadcastBuf = 256 DefaultRegisterBuf = 64 DefaultChannelTimeout = 5 * time.Second )
Variables ¶
var (
ErrHubStopped = errors.New("wskit: hub is stopped")
)
Functions ¶
This section is empty.
Types ¶
type AcceptFunc ¶
type AcceptFunc func(w http.ResponseWriter, r *http.Request, opts *websocket.AcceptOptions) (*websocket.Conn, error)
AcceptFunc is the type of websocket.Accept for dependency injection.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client represents a single WebSocket connection attached to a Hub.
func Accept ¶
func Accept(ctx context.Context, w http.ResponseWriter, r *http.Request, hub *Hub, acceptOpts *websocket.AcceptOptions, clientOpts ...ClientOption) (*Client, error)
Accept upgrades the HTTP connection to WebSocket, creates a Client, and registers it with the hub. Caller should run ReadPump and WritePump in goroutines. acceptOpts may be nil for default upgrade options.
func NewClient ¶
NewClient creates a client for the given hub and connection. Call Register on the hub, then run ReadPump and WritePump in separate goroutines.
func (*Client) ReadPump ¶
func (c *Client) ReadPump()
ReadPump reads messages from the connection until it closes or errors. On exit it unregisters the client and closes the connection. Run in a goroutine.
func (*Client) Send ¶
Send enqueues data for writing. Non-blocking; returns false if the send buffer is full or the client is unregistered.
type ClientConfig ¶
type ClientOption ¶
type ClientOption func(*ClientConfig)
ClientOption configures a Client.
func WithMaxMessageSize ¶
func WithMaxMessageSize(n int64) ClientOption
WithMaxMessageSize sets the maximum size of a single incoming message.
func WithPingInterval ¶
func WithPingInterval(d time.Duration) ClientOption
WithPingInterval sets the interval between ping frames.
func WithSendBufSize ¶
func WithSendBufSize(n int) ClientOption
WithSendBufSize sets the send channel buffer size.
func WithWriteWait ¶
func WithWriteWait(d time.Duration) ClientOption
WithWriteWait sets the timeout for writing a message or ping.
type Conn ¶
type Conn interface {
Read(ctx context.Context) (websocket.MessageType, []byte, error)
Writer(ctx context.Context, typ websocket.MessageType) (io.WriteCloser, error)
Close(code websocket.StatusCode, reason string) error
Ping(ctx context.Context) error
SetReadLimit(limit int64)
}
Conn abstracts a WebSocket connection for testing and alternate implementations.
type Event ¶
type Event struct {
Type string `json:"type"`
Payload any `json:"payload"`
Timestamp time.Time `json:"timestamp"`
}
Event is the default envelope for WebSocket messages: type, payload, and timestamp.
type Hub ¶
type Hub struct {
// contains filtered or unexported fields
}
Hub is the central dispatcher for WebSocket clients. Run one goroutine with Run(ctx).
func (*Hub) BroadcastEvent ¶
BroadcastEvent marshals event as JSON and broadcasts it. If Redis is configured, publishes to Redis first; on failure falls back to local Broadcast. Returns an error only when JSON marshaling fails.
func (*Hub) BroadcastJSON ¶
BroadcastJSON marshals Event{typ, payload, now} and broadcasts it via the hub. Returns an error if JSON marshaling fails.
func (*Hub) ClientCount ¶
ClientCount returns the number of registered clients.
func (*Hub) SubscribeToRedis ¶
SubscribeToRedis subscribes to the hub's Redis channel and broadcasts received messages to all clients. Run in a goroutine; it returns when ctx is cancelled.
func (*Hub) Unregister ¶
Unregister removes the client from the hub. Non-blocking with timeout.
type HubOption ¶
type HubOption func(*Hub)
HubOption configures a Hub.
func WithBroadcastBuf ¶
WithBroadcastBuf sets the broadcast channel buffer size.
func WithChannelTimeout ¶
WithChannelTimeout sets the timeout for Register, Unregister, and Broadcast operations.
func WithOnConnect ¶
WithOnConnect sets the callback invoked when a client registers.
func WithOnTimeout ¶
WithOnTimeout sets a callback when a channel operation times out (e.g. for logging).
func WithRedis ¶
WithRedis configures Redis Pub/Sub for multi-instance broadcast. If client is nil, Redis is disabled.
func WithRegisterBuf ¶
WithRegisterBuf sets the register/unregister channel buffer size.