websocket

package
v0.39.0 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2026 License: Apache-2.0 Imports: 9 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	SessionID string
	SubjectID string
	Rooms     map[string]bool
	Meta      map[string]any
	// contains filtered or unexported fields
}

Client represents a single WebSocket connection managed by a Hub.

type Emitter

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

Emitter is a thin typed wrapper over Hub that accepts *Event values instead of raw bytes.

func NewEmitter

func NewEmitter(hub *Hub) *Emitter

NewEmitter creates an Emitter backed by the given Hub.

func (*Emitter) Broadcast

func (e *Emitter) Broadcast(event *Event)

Broadcast sends an event to every connected client.

func (*Emitter) ToRoom

func (e *Emitter) ToRoom(room string, event *Event)

ToRoom sends an event to all clients in a room.

func (*Emitter) ToRoomExcept

func (e *Emitter) ToRoomExcept(room string, event *Event, exceptSessionID string)

ToRoomExcept sends an event to all room clients except one session.

func (*Emitter) ToSession

func (e *Emitter) ToSession(sessionID string, event *Event)

ToSession sends an event to a single session.

func (*Emitter) ToSubject

func (e *Emitter) ToSubject(subjectID string, event *Event)

ToSubject sends an event to all sessions for a subject.

type Event

type Event struct {
	Type    EventType       `json:"type"`
	Payload json.RawMessage `json:"payload,omitempty"`
	Target  string          `json:"target,omitempty"`  // CSS selector
	Swap    string          `json:"swap,omitempty"`    // "innerHTML" or "outerHTML"
	HTML    string          `json:"html,omitempty"`    // rendered HTML to swap in
	Trigger string          `json:"trigger,omitempty"` // HTMX event name
}

Event is the standard WebSocket event structure. Supports three delivery modes:

  1. HTML Direct: set Target + HTML, client swaps HTML into target
  2. HTMX Trigger: set Target + Trigger, client calls htmx.trigger()
  3. Data Only: set Payload only, client handles via registered callback

func NewEvent

func NewEvent(eventType EventType, payload any) *Event

NewEvent creates a data-only event with a JSON-marshaled payload.

func NewHTMLEvent

func NewHTMLEvent(eventType EventType, target, html string) *Event

NewHTMLEvent creates an event that swaps HTML into a target element (innerHTML).

func NewOuterHTMLEvent

func NewOuterHTMLEvent(eventType EventType, target, html string) *Event

NewOuterHTMLEvent creates an event that replaces a target element entirely (outerHTML).

func NewTriggerEvent

func NewTriggerEvent(eventType EventType, target, trigger string) *Event

NewTriggerEvent creates an event that triggers an HTMX event on a target.

func (*Event) JSON

func (e *Event) JSON() []byte

JSON serializes the event to JSON bytes.

type EventType

type EventType string

EventType represents the type of WebSocket event. No domain-specific constants are defined here — projects define their own.

type Hub

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

Hub manages WebSocket clients with session, subject, and room routing. It uses a pure mutex design with no background event-loop goroutine.

func NewHub

func NewHub(opts ...HubOption) *Hub

NewHub creates a Hub with the given options.

func (*Hub) AssociateSubject

func (h *Hub) AssociateSubject(sessionID, subjectID string)

AssociateSubject associates a session with a subject ID at runtime (e.g. after authentication completes post-connection).

func (*Hub) Broadcast

func (h *Hub) Broadcast(msg []byte) int

Broadcast sends a message to every connected client. Returns the number of dropped messages.

func (*Hub) Close

func (h *Hub) Close()

Close cancels the hub context, waits for all pumps to exit, and clears maps. Safe to call multiple times.

func (*Hub) Handler

func (h *Hub) Handler() echo.HandlerFunc

Handler returns an Echo handler that upgrades HTTP connections to WebSocket.

func (*Hub) JoinRoom

func (h *Hub) JoinRoom(c *Client, room string)

JoinRoom adds a client to a room. No-op if the client is no longer the registered client for its session (e.g. it disconnected, or was replaced by a reconnect): adding a stale client whose send channel is already closed would make the next SendToRoom/Broadcast panic on send-to-closed-channel.

func (*Hub) LeaveRoom

func (h *Hub) LeaveRoom(c *Client, room string)

LeaveRoom removes a client from a room.

func (*Hub) SendToRoom

func (h *Hub) SendToRoom(room string, msg []byte) int

SendToRoom sends a message to all clients in a room. Returns the number of dropped messages.

func (*Hub) SendToRoomExcept

func (h *Hub) SendToRoomExcept(room string, msg []byte, exceptSessionID string) int

SendToRoomExcept sends a message to all clients in a room except one session. Returns the number of dropped messages.

func (*Hub) SendToSession

func (h *Hub) SendToSession(sessionID string, msg []byte) bool

SendToSession sends a message to the client with the given session ID. Returns true if the message was sent, false if the session was not found or the message was dropped.

func (*Hub) SendToSubject

func (h *Hub) SendToSubject(subjectID string, msg []byte) int

SendToSubject sends a message to all clients associated with a subject ID. Returns the number of dropped messages.

func (*Hub) Stats

func (h *Hub) Stats() HubStats

Stats returns current hub connection counts.

type HubOption

type HubOption func(*Hub)

HubOption configures a Hub.

func WithAcceptOptions

func WithAcceptOptions(opts *ws.AcceptOptions) HubOption

WithAcceptOptions sets the websocket.AcceptOptions used when upgrading.

func WithLogger

func WithLogger(l *slog.Logger) HubOption

WithLogger sets the logger for the hub. Defaults to slog.Default().

func WithOnMessage

func WithOnMessage(fn func(*Client, []byte)) HubOption

WithOnMessage registers a callback invoked for every inbound client message. When nil (the default), the hub operates in server-push-only mode.

func WithSendBufferSize

func WithSendBufferSize(n int) HubOption

WithSendBufferSize sets the per-client send channel buffer size. Default: 256. Values <= 0 are treated as the default.

func WithSessionIDFunc

func WithSessionIDFunc(fn func(r *http.Request) string) HubOption

WithSessionIDFunc sets the function used to derive a session ID from the HTTP request. The default generates a random UUID.

func WithSubjectIDFunc

func WithSubjectIDFunc(fn func(r *http.Request) string) HubOption

WithSubjectIDFunc sets the function used to derive a subject (user) ID from the HTTP request. When nil (the default), no subject tracking occurs.

type HubStats

type HubStats struct {
	Clients  int
	Subjects int
	Rooms    int
}

HubStats contains hub connection counts.

Jump to

Keyboard shortcuts

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