ws

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Jul 3, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Index

Constants

View Source
const (
	EventSubscribe   = "subscribe"
	EventUnsubscribe = "unsubscribe"
	EventPing        = "ping"
	EventPong        = "pong"
)

Variables

This section is empty.

Functions

func Mount

func Mount(target route.Target, hub *Hub)

Mount mounts a hub websocket endpoint on a route target.

func Provider

func Provider(hubs ...*Hub) provider.Provider

Provider registers websocket hubs as host units.

Types

type Authenticator

type Authenticator func(ctx *route.Context) (*Identity, error)

Authenticator authenticates a websocket handshake.

type Broker

type Broker interface {
	Publish(ctx context.Context, channel string, packet Packet) error
	Subscribe(ctx context.Context, node string, fn func(Packet) error) error
	Close(ctx context.Context) error
}

Broker coordinates packets across nodes.

func MessageBroker

func MessageBroker(driver message.Driver, topics ...string) Broker

MessageBroker adapts a message broker driver for distributed websocket packets.

func NewMemoryBroker

func NewMemoryBroker() Broker

NewMemoryBroker creates an in-process broker.

type ChannelInfo

type ChannelInfo struct {
	Name    string `json:"name"`
	Clients int    `json:"clients"`
}

ChannelInfo describes one channel.

type Client

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

Client is one active websocket connection.

func (*Client) Close

func (client *Client) Close(reason CloseReason) error

Close closes this client.

func (*Client) ID

func (client *Client) ID() string

ID returns client id.

func (*Client) Identity

func (client *Client) Identity() Identity

Identity returns client identity snapshot.

func (*Client) Send

func (client *Client) Send(event string, data any) error

Send sends an event to this client.

func (*Client) Subscribe

func (client *Client) Subscribe(channel string) error

Subscribe subscribes this client to a channel.

func (*Client) Unsubscribe

func (client *Client) Unsubscribe(channel string) error

Unsubscribe unsubscribes this client from a channel.

type ClientInfo

type ClientInfo struct {
	ID        string    `json:"id"`
	Name      string    `json:"name,omitempty"`
	Node      string    `json:"node,omitempty"`
	Channels  []string  `json:"channels,omitempty"`
	Connected time.Time `json:"connected"`
	LastSeen  time.Time `json:"last_seen"`
	IP        string    `json:"ip,omitempty"`
	UserAgent string    `json:"user_agent,omitempty"`
	Meta      core.Map  `json:"meta,omitempty"`
}

ClientInfo describes one online client.

type CloseReason

type CloseReason string

CloseReason is a human-readable close reason.

type Config

type Config struct {
	Auth Authenticator `toml:"-"`

	Origin []string `toml:"origin"`

	MaxMessageSize int64         `toml:"max_message_size"`
	ReadTimeout    time.Duration `toml:"read_timeout"`
	WriteTimeout   time.Duration `toml:"write_timeout"`
	PingInterval   time.Duration `toml:"ping_interval"`
	PongTimeout    time.Duration `toml:"pong_timeout"`

	SendBuffer int      `toml:"send_buffer"`
	Broker     Broker   `toml:"-"`
	Presence   Presence `toml:"-"`
	Node       string   `toml:"node"`
}

Config configures a websocket hub.

type Context

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

Context is one websocket message handling context.

func (*Context) Bind

func (ctx *Context) Bind(output any) error

Bind decodes message data into output.

func (*Context) Can

func (ctx *Context) Can(name string) error

Can checks metadata permission flag.

func (*Context) Client

func (ctx *Context) Client() *Client

Client returns current client.

func (*Context) Context

func (ctx *Context) Context() context.Context

Context returns current message context.

func (*Context) Error

func (ctx *Context) Error(code string, message string) error

Error writes an error response for current message.

func (*Context) Hub

func (ctx *Context) Hub() *Hub

Hub returns current hub.

func (*Context) Identity

func (ctx *Context) Identity() Identity

Identity returns current client identity.

func (*Context) Message

func (ctx *Context) Message() Message

Message returns current message.

func (*Context) Publish

func (ctx *Context) Publish(channel string, event string, data any) error

Publish publishes a packet to a channel.

func (*Context) Reply

func (ctx *Context) Reply(data any) error

Reply writes a response for current message.

func (*Context) Scope

func (ctx *Context) Scope() *scope.Scope

Scope returns current message scope.

func (*Context) Send

func (ctx *Context) Send(event string, data any) error

Send sends an event to current client.

func (*Context) SetContext

func (ctx *Context) SetContext(value context.Context)

SetContext replaces current message context.

func (*Context) Subscribe

func (ctx *Context) Subscribe(channel string) error

Subscribe subscribes current client to a channel.

func (*Context) Unsubscribe

func (ctx *Context) Unsubscribe(channel string) error

Unsubscribe unsubscribes current client from a channel.

type Filter

type Filter func(ClientInfo) bool

Filter filters client info.

func ByChannel

func ByChannel(channel string) Filter

ByChannel filters clients by channel.

func ByID

func ByID(id string) Filter

ByID filters clients by id.

type Handler

type Handler func(ctx *Context) error

Handler handles one websocket message.

type Hub

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

Hub manages websocket clients and channels.

func New

func New(name string, config Config) *Hub

New creates a websocket hub.

func (*Hub) Broadcast

func (hub *Hub) Broadcast(event string, data any) error

Broadcast sends an event to all connected clients.

func (*Hub) BroadcastContext

func (hub *Hub) BroadcastContext(ctx context.Context, event string, data any) error

BroadcastContext sends an event to all connected clients.

func (*Hub) Channel

func (hub *Hub) Channel(name string) ChannelInfo

Channel returns one channel stats.

func (*Hub) Channels

func (hub *Hub) Channels() []ChannelInfo

Channels returns channel stats.

func (*Hub) Check

func (hub *Hub) Check(context.Context) host.Health

Check returns host health.

func (*Hub) Client

func (hub *Hub) Client(id string) (*ClientInfo, bool)

Client returns one client info.

func (*Hub) Clients

func (hub *Hub) Clients(filters ...Filter) []ClientInfo

Clients returns online clients.

func (*Hub) Configure added in v0.1.2

func (hub *Hub) Configure(config Config) *Hub

Configure merges runtime hub configuration.

func (*Hub) HostName

func (hub *Hub) HostName() string

HostName returns host unit name.

func (*Hub) Kick

func (hub *Hub) Kick(clientID string, reason CloseReason) error

Kick closes one client.

func (*Hub) KickChannel

func (hub *Hub) KickChannel(channel string, reason CloseReason) error

KickChannel closes all clients subscribed to a channel.

func (*Hub) KickMany

func (hub *Hub) KickMany(clientIDs []string, reason CloseReason) error

KickMany closes many clients.

func (*Hub) Name

func (hub *Hub) Name() string

Name returns hub name.

func (*Hub) On

func (hub *Hub) On(event string, handler Handler) *Hub

On registers an event handler.

func (*Hub) OnPublish

func (hub *Hub) OnPublish(fn PublishHook) *Hub

OnPublish registers publish hook.

func (*Hub) OnSubscribe

func (hub *Hub) OnSubscribe(fn SubscribeHook) *Hub

OnSubscribe registers subscription hook.

func (*Hub) Publish

func (hub *Hub) Publish(channel string, event string, data any) error

Publish publishes an event to a channel.

func (*Hub) PublishContext

func (hub *Hub) PublishContext(ctx context.Context, channel string, event string, data any) error

PublishContext publishes an event to a channel.

func (*Hub) Send

func (hub *Hub) Send(clientID string, event string, data any) error

Send sends an event to one client.

func (*Hub) SendContext

func (hub *Hub) SendContext(ctx context.Context, clientID string, event string, data any) error

SendContext sends an event to one client.

func (*Hub) SendMany

func (hub *Hub) SendMany(clientIDs []string, event string, data any) error

SendMany sends an event to many clients.

func (*Hub) Serve

func (hub *Hub) Serve(ctx *route.Context) error

Serve upgrades HTTP request to websocket and serves messages.

func (*Hub) Start

func (hub *Hub) Start(ctx context.Context) error

Start subscribes the broker and marks hub active.

func (*Hub) Stats

func (hub *Hub) Stats() Stats

Stats returns hub runtime stats.

func (*Hub) Status

func (hub *Hub) Status() host.Status

Status returns host status.

func (*Hub) Stop

func (hub *Hub) Stop(ctx context.Context) error

Stop closes all clients and dependencies.

func (*Hub) Use

func (hub *Hub) Use(middlewares ...Middleware) *Hub

Use adds websocket event middleware.

type Identity

type Identity struct {
	ID   string
	Name string
	Meta core.Map
}

Identity is the authenticated websocket client snapshot.

type Message

type Message struct {
	ID      string       `json:"id,omitempty"`
	Event   string       `json:"event"`
	Channel string       `json:"channel,omitempty"`
	Data    core.JSONRaw `json:"data,omitempty"`
	Meta    core.Map     `json:"meta,omitempty"`
}

Message is a client-to-server websocket message.

type Middleware

type Middleware func(Handler) Handler

Middleware wraps websocket event handling.

type Packet

type Packet struct {
	Channel string   `json:"channel,omitempty"`
	Event   string   `json:"event"`
	Data    any      `json:"data,omitempty"`
	Meta    core.Map `json:"meta,omitempty"`
	Origin  string   `json:"origin,omitempty"`
}

Packet is a server push packet.

type Presence

type Presence interface {
	Set(ctx context.Context, client ClientInfo) error
	Remove(ctx context.Context, clientID string) error
	Clients(ctx context.Context, filter ...Filter) ([]ClientInfo, error)
	Channels(ctx context.Context) ([]ChannelInfo, error)
	Close(ctx context.Context) error
}

Presence stores online client state.

func NewMemoryPresence

func NewMemoryPresence() Presence

NewMemoryPresence creates in-process presence storage.

type PublishHook

type PublishHook func(ctx context.Context, channel string, event string, data any) error

PublishHook runs before publishing a packet.

type Registry

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

Registry stores app-scoped websocket hubs.

func (*Registry) Add

func (registry *Registry) Add(hubs ...*Hub)

func (*Registry) Hubs

func (registry *Registry) Hubs() []*Hub

type Response

type Response struct {
	ID      string   `json:"id,omitempty"`
	Event   string   `json:"event,omitempty"`
	OK      bool     `json:"ok"`
	Code    string   `json:"code,omitempty"`
	Message string   `json:"message,omitempty"`
	Data    any      `json:"data,omitempty"`
	Meta    core.Map `json:"meta,omitempty"`
}

Response is a server-to-client websocket response.

type Stats

type Stats struct {
	Clients     int    `json:"clients"`
	Channels    int    `json:"channels"`
	MessagesIn  uint64 `json:"messages_in"`
	MessagesOut uint64 `json:"messages_out"`
	BytesIn     uint64 `json:"bytes_in"`
	BytesOut    uint64 `json:"bytes_out"`
}

Stats describes hub runtime counters.

type SubscribeHook

type SubscribeHook func(ctx *Context, channel string) error

SubscribeHook checks a subscription request.

Jump to

Keyboard shortcuts

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