ws

package
v0.83.4 Latest Latest
Warning

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

Go to latest
Published: May 23, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package ws wires WebSocket endpoints onto a Gin engine using gorilla/websocket and records metadata about them in the nexus registry.

Index

Constants

View Source
const (
	EventTypeConnected    = "connection.established"
	EventTypeDisconnected = "connection.closed"
	EventTypeError        = "error"
	EventTypePong         = "pong"
	EventTypeSubscribed   = "subscribed"
	EventTypeUnsubscribed = "unsubscribed"
	EventTypeAuthed       = "authenticated"
)

Built-in event types. Keep the string values stable — clients depend on them.

Variables

This section is empty.

Functions

This section is empty.

Types

type Builder

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

func New

func New(e *gin.Engine, r *registry.Registry, bus *trace.Bus, service, path string) *Builder

func (*Builder) Describe

func (b *Builder) Describe(s string) *Builder

func (*Builder) Mount

func (b *Builder) Mount()

Mount attaches the WebSocket endpoint to Gin and records it in the registry. Terminal.

Tracing: NO trace.Middleware on the upgrade route. WS upgrade is a one-time HTTP request that promotes to a long-lived connection; wrapping it in request.start/request.end would keep one trace open for the entire connection lifetime (until close) and produce no renderable spans. Per-frame traces are emitted inside b.serve's read loop instead — each frame becomes its own root trace on the dashboard's waterfall, matching how AsWS's typed dispatcher does it.

func (*Builder) OnClose

func (b *Builder) OnClose(fn CloseFunc) *Builder

func (*Builder) OnConnect

func (b *Builder) OnConnect(fn ConnectFunc) *Builder

func (*Builder) OnMessage

func (b *Builder) OnMessage(fn MessageFunc) *Builder

func (*Builder) Tag

func (b *Builder) Tag(k, v string) *Builder

func (*Builder) Upgrader

func (b *Builder) Upgrader(u websocket.Upgrader) *Builder

func (*Builder) Use

func (b *Builder) Use(name string, mw gin.HandlerFunc) *Builder

func (*Builder) WithHub

func (b *Builder) WithHub(h *Hub) *Builder

WithHub hands connection management to a Hub: rooms, user/client-targeted events, broadcast, worker-pool fan-out, slow-client backpressure, and the default subscribe/authenticate/ping message protocol all become available. When a hub is set, OnConnect/OnMessage/OnClose on the Builder are ignored — install hooks on the Hub instead (hub.OnMessage, hub.OnConnect, ...).

type CloseFunc

type CloseFunc func(conn *websocket.Conn)

type ConnectFunc

type ConnectFunc func(c *gin.Context, conn *websocket.Conn) error

type Connection

type Connection struct {
	ClientID string
	UserID   string
	Metadata map[string]any
	// contains filtered or unexported fields
}

Connection is one authenticated WebSocket client.

func (*Connection) Send

func (c *Connection) Send(message []byte)

Send queues a raw message. If the send buffer is repeatedly full the hub closes the connection — slow clients do not hold up the fan-out loop.

func (*Connection) SendEvent

func (c *Connection) SendEvent(e *Event) error

SendEvent marshals and sends an Event to this single connection.

type Event

type Event struct {
	Type      string       `json:"type"`
	Data      any          `json:"data"`
	Timestamp int64        `json:"timestamp"`
	Target    *EventTarget `json:"-"`
}

Event is the envelope the hub sends to clients. Target decides recipients.

func NewEvent

func NewEvent(eventType string, data any) *Event

NewEvent builds an Event with the current unix timestamp and a broadcast target.

func (*Event) ToBroadcast

func (e *Event) ToBroadcast() *Event

func (*Event) ToClient

func (e *Event) ToClient(clientIDs ...string) *Event

func (*Event) ToRoom

func (e *Event) ToRoom(rooms ...string) *Event

func (*Event) ToUser

func (e *Event) ToUser(userIDs ...string) *Event

type EventTarget

type EventTarget struct {
	Broadcast bool
	UserIDs   []string
	ClientIDs []string
	Rooms     []string
}

EventTarget specifies which connections receive an Event.

type Hub

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

Hub is a pub/sub engine for a pool of WebSocket connections with rooms, user-/client-targeted events, and a fan-out worker pool.

func NewHub

func NewHub(opts ...HubOption) *Hub

NewHub creates a hub with default settings. Call Start() (or pass it to a Builder that calls Start for you) before mounting endpoints on it.

func (*Hub) BroadcastRaw added in v0.9.0

func (h *Hub) BroadcastRaw(data []byte)

BroadcastRaw queues a raw byte payload to every connection without wrapping it in an Event envelope. Intended for higher-level APIs (e.g. AsWS) that manage their own envelope — drop an already-marshalled message straight onto the fan-out worker pool. Drops silently if the broadcast channel is full.

func (*Hub) ConnectionCount

func (h *Hub) ConnectionCount() int

func (*Hub) Emit

func (h *Hub) Emit(e *Event)

Emit queues an event for fan-out. Dropped silently if the event channel is full — callers trade completeness for backpressure.

func (*Hub) EmitBroadcast

func (h *Hub) EmitBroadcast(eventType string, data any)

func (*Hub) EmitToClients

func (h *Hub) EmitToClients(eventType string, data any, clientIDs ...string)

func (*Hub) EmitToRoom

func (h *Hub) EmitToRoom(eventType string, data any, room string)

func (*Hub) EmitToUsers

func (h *Hub) EmitToUsers(eventType string, data any, userIDs ...string)

func (*Hub) Join

func (h *Hub) Join(conn *Connection, room string)

Join subscribes a connection to a room. Idempotent.

func (*Hub) Leave

func (h *Hub) Leave(conn *Connection, room string)

Leave unsubscribes a connection from a room.

func (*Hub) OnConnect

func (h *Hub) OnConnect(fn OnConnectFunc) *Hub

func (*Hub) OnDisconnect

func (h *Hub) OnDisconnect(fn OnDisconnectFunc) *Hub

func (*Hub) OnIdentify

func (h *Hub) OnIdentify(fn IdentifyFunc) *Hub

Hooks — fluent setters.

func (*Hub) OnMessage

func (h *Hub) OnMessage(fn OnMessageFunc) *Hub

func (*Hub) RoomConnectionCount

func (h *Hub) RoomConnectionCount(room string) int

func (*Hub) Rooms

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

Rooms returns a snapshot of room names and their member counts. Cheap for dashboards; do not call on the hot path.

func (*Hub) Serve added in v0.9.0

func (h *Hub) Serve(gctx *gin.Context, upgrader websocket.Upgrader)

Serve handles one HTTP upgrade request using the supplied upgrader: it upgrades the connection, runs the identify hook, registers the conn with the hub, and starts the read/write pumps. Exposed for callers (notably the nexus.AsWS path) that mount the hub on their own gin route and need the upgrade behavior without going through ws.Builder.

For the no-op upgrader default (AllowAll origins), see ServeGin — a zero-config sibling.

func (*Hub) ServeGin added in v0.9.0

func (h *Hub) ServeGin(gctx *gin.Context)

ServeGin is Serve with the hub's default upgrader (CheckOrigin: always true). Convenient for callers that don't need to customize upgrade behavior — matches the upgrader the Builder installs.

func (*Hub) Start

func (h *Hub) Start(ctx context.Context)

Start spins up the hub's main loop and the broadcast worker pool. Safe to call repeatedly — only the first call starts goroutines.

func (*Hub) Stop

func (h *Hub) Stop()

Stop cancels the hub context, closes every connection, and returns. Idempotent.

func (*Hub) UserConnectionCount

func (h *Hub) UserConnectionCount(userID string) int

type HubOption

type HubOption func(*hubConfig)

HubOption configures a Hub at construction.

func WithEventBuffer

func WithEventBuffer(n int) HubOption

func WithLogger

func WithLogger(fn func(format string, args ...any)) HubOption

func WithMaxConnections

func WithMaxConnections(n int) HubOption

func WithMaxMessageSize

func WithMaxMessageSize(n int64) HubOption

func WithPingPong

func WithPingPong(pong, write time.Duration) HubOption

func WithWorkers

func WithWorkers(n int) HubOption

type IdentifyFunc

type IdentifyFunc func(c *gin.Context) (userID string, meta map[string]any)

Hooks the caller can install.

type MessageFunc

type MessageFunc func(conn *websocket.Conn, msgType int, data []byte) error

type OnConnectFunc

type OnConnectFunc func(conn *Connection)

Hooks the caller can install.

type OnDisconnectFunc

type OnDisconnectFunc func(conn *Connection)

Hooks the caller can install.

type OnMessageFunc

type OnMessageFunc func(conn *Connection, msgType int, data []byte) error

Hooks the caller can install.

Jump to

Keyboard shortcuts

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