Documentation
¶
Index ¶
- Constants
- Variables
- func HeartbeatHandler(c *Context) *jsonrpc.Response
- func IsValidPlatform(p string) bool
- func RequestID(ctx context.Context) string
- func SubscribeHandler(c *Context) *jsonrpc.Response
- func UnsubscribeHandler(c *Context) *jsonrpc.Response
- func UserID(ctx context.Context) string
- func WithRequestID(ctx context.Context, requestID string) context.Context
- func WithUserID(ctx context.Context, userID string) context.Context
- type Client
- func (c *Client) GetPlatform() string
- func (c *Client) GetUserID() string
- func (c *Client) Heartbeat(currentTime int64)
- func (c *Client) HeartbeatTime() int64
- func (c *Client) IsAuthenticated() bool
- func (c *Client) IsHeartbeatTimeout(currentTime int64) bool
- func (c *Client) Login(platform, userID string, loginTime int64)
- func (c *Client) NotifyLogin(userID, platform string, tokenExpiresAt int64)
- func (c *Client) ParseToken(token string) (*TokenInfo, error)
- func (c *Client) ReadPump()
- func (c *Client) SendJSON(v any)
- func (c *Client) UpdateContext(userID string)
- func (c *Client) WritePump()
- type ClientDisconnectCallback
- type ClientOption
- type Context
- type ContextUpdater
- type Error
- type Group
- type Handler
- type Hub
- func (h *Hub) AnonymousCount() int
- func (h *Hub) CanAcceptConnection() bool
- func (h *Hub) CanUserConnect(userID string) bool
- func (h *Hub) ClientCount() int
- func (h *Hub) Done() <-chan struct{}
- func (h *Hub) GetClient(clientID string) *Client
- func (h *Hub) GetClientsByUser(userID string) []*Client
- func (h *Hub) GetUserClient(platform, userID string) *Client
- func (h *Hub) KickClient(clientID string, reason string) bool
- func (h *Hub) KickUser(userID string, reason string) int
- func (h *Hub) Metrics() *Metrics
- func (h *Hub) PushToTopic(topic, method string, data any)
- func (h *Hub) PushToUser(platform, userID, method string, data any)
- func (h *Hub) PushToUserAllPlatforms(userID, method string, data any)
- func (h *Hub) Run(ctx context.Context)
- func (h *Hub) Stats() *HubStats
- func (h *Hub) TopicCount() int
- func (h *Hub) TotalConnections() int
- func (h *Hub) UserConnectionCount(userID string) int
- func (h *Hub) UserCount() int
- type HubConfig
- type HubOption
- type HubStats
- type Logger
- type LoginEvent
- type Metrics
- type Middleware
- type Router
- type SubscribeEvent
- type TokenInfo
- type TokenParser
- type UnsubscribeEvent
Constants ¶
const ( PlatformWeb = "web" PlatformIOS = "ios" PlatformAndroid = "android" PlatformH5 = "h5" PlatformMiniApp = "miniapp" PlatformDesktop = "desktop" )
Platform constants.
Variables ¶
var FromError = errors.FromError
FromError converts an error to *Error.
var NewError = errors.New
NewError creates a new Error with the given code, reason, and formatted message.
Functions ¶
func HeartbeatHandler ¶
HeartbeatHandler responds to heartbeat requests.
func IsValidPlatform ¶
IsValidPlatform checks if the platform string is valid.
func SubscribeHandler ¶
SubscribeHandler handles topic subscription.
func UnsubscribeHandler ¶
UnsubscribeHandler handles topic unsubscription.
func WithRequestID ¶
WithRequestID stores the request ID in the context.
Types ¶
type Client ¶
type Client struct {
// Send channel for outbound messages
Send chan []byte
// Client info
ID string // Unique client identifier
Addr string
FirstTime int64
TokenExpiresAt int64
Platform string
UserID string
LoginTime int64
// contains filtered or unexported fields
}
Client represents a WebSocket client connection.
func (*Client) GetPlatform ¶ added in v0.2.1
GetPlatform returns the platform (thread-safe).
func (*Client) HeartbeatTime ¶
HeartbeatTime returns the last heartbeat time.
func (*Client) IsAuthenticated ¶
IsAuthenticated returns true if the client has logged in.
func (*Client) IsHeartbeatTimeout ¶
IsHeartbeatTimeout returns true if heartbeat has timed out.
func (*Client) NotifyLogin ¶
NotifyLogin sends a login event to the hub.
func (*Client) ParseToken ¶
ParseToken parses a JWT token using the client's token parser.
func (*Client) ReadPump ¶
func (c *Client) ReadPump()
ReadPump pumps messages from the websocket connection to the hub.
func (*Client) UpdateContext ¶
UpdateContext updates the client context with user info.
type ClientDisconnectCallback ¶
type ClientDisconnectCallback func(client *Client)
ClientDisconnectCallback is called when a client disconnects.
type ClientOption ¶
type ClientOption func(*Client)
ClientOption is a functional option for configuring Client.
func WithContextUpdater ¶
func WithContextUpdater(updater ContextUpdater) ClientOption
WithContextUpdater sets a context updater for the client.
func WithTokenParser ¶
func WithTokenParser(parser TokenParser) ClientOption
WithTokenParser sets a token parser for the client.
type Context ¶
type Context struct {
context.Context
Request *jsonrpc.Request
Client *Client
Method string
StartTime time.Time
}
Context contains all information needed by middleware. It embeds context.Context so it can be passed directly to business layer methods.
func (*Context) BindParams ¶
BindParams unmarshals the request params into the given struct.
func (*Context) BindValidate ¶
BindValidate unmarshals and validates the request params.
type ContextUpdater ¶
ContextUpdater updates the client context with user info after login.
type Group ¶
type Group struct {
// contains filtered or unexported fields
}
Group is a collection of handlers with shared middleware.
func (*Group) Handle ¶
func (g *Group) Handle(method string, handler Handler, middlewares ...Middleware)
Handle registers a handler in this group.
func (*Group) Use ¶
func (g *Group) Use(middlewares ...Middleware) *Group
Use adds middleware to this group.
type Hub ¶
type Hub struct {
// Channels for events
Register chan *Client
Unregister chan *Client
Login chan *LoginEvent
Broadcast chan []byte
Subscribe chan *SubscribeEvent
Unsubscribe chan *UnsubscribeEvent
// contains filtered or unexported fields
}
Hub maintains the set of active clients and manages their lifecycle.
func NewHubWithConfig ¶
NewHubWithConfig creates a new Hub with custom config.
func (*Hub) AnonymousCount ¶
AnonymousCount returns the number of anonymous connections.
func (*Hub) CanAcceptConnection ¶ added in v0.2.0
CanAcceptConnection returns true if a new connection can be accepted. Returns false if MaxConnections limit would be exceeded.
func (*Hub) CanUserConnect ¶ added in v0.2.0
CanUserConnect returns true if the user can establish another connection. Returns false if MaxConnsPerUser limit would be exceeded.
func (*Hub) ClientCount ¶
ClientCount returns the number of authenticated clients.
func (*Hub) Done ¶ added in v0.2.1
func (h *Hub) Done() <-chan struct{}
Done returns a channel that's closed when the hub is shutting down.
func (*Hub) GetClientsByUser ¶
GetClientsByUser returns all clients for a user across all platforms.
func (*Hub) GetUserClient ¶
GetUserClient returns the client for a user.
func (*Hub) KickClient ¶
KickClient disconnects a client by ID.
func (*Hub) PushToTopic ¶
PushToTopic sends a message to all subscribers of a topic.
func (*Hub) PushToUser ¶
PushToUser sends a message to a specific user on a specific platform.
func (*Hub) PushToUserAllPlatforms ¶
PushToUserAllPlatforms sends a message to a user on all connected platforms.
func (*Hub) TopicCount ¶
TopicCount returns the number of topics with subscribers.
func (*Hub) TotalConnections ¶ added in v0.2.0
TotalConnections returns the total number of connections (anonymous + authenticated).
func (*Hub) UserConnectionCount ¶ added in v0.2.0
UserConnectionCount returns the number of connections for a user across all platforms.
type HubConfig ¶
type HubConfig struct {
// Anonymous connection timeout (must login within this time)
AnonymousTimeout time.Duration
// Anonymous connection cleanup interval
AnonymousCleanup time.Duration
// Authenticated connection heartbeat timeout
HeartbeatTimeout time.Duration
// Authenticated connection cleanup interval
HeartbeatCleanup time.Duration
// WebSocket protocol ping period
PingPeriod time.Duration
// WebSocket protocol pong wait timeout
PongWait time.Duration
// Client connection settings
MaxMessageSize int64 // Maximum message size allowed from peer
WriteWait time.Duration // Time allowed to write a message to the peer
// Connection limits (0 = unlimited)
MaxConnections int // Maximum total connections
MaxConnsPerUser int // Maximum connections per user (across all platforms)
}
HubConfig holds configuration for the Hub.
func DefaultHubConfig ¶
func DefaultHubConfig() *HubConfig
DefaultHubConfig returns default configuration.
type HubOption ¶
type HubOption func(*Hub)
HubOption is a functional option for configuring Hub.
func WithClientDisconnectCallback ¶
func WithClientDisconnectCallback(cb ClientDisconnectCallback) HubOption
WithClientDisconnectCallback sets a callback for client disconnect events. Use this to clean up resources when a client disconnects.
func WithMetrics ¶ added in v0.2.0
WithMetrics sets the Prometheus metrics for the hub.
type HubStats ¶
type HubStats struct {
TotalConnections int64
AuthenticatedConns int64
AnonymousConns int64
ConnectionsByPlatform map[string]int
}
HubStats contains hub statistics.
type Logger ¶
type Logger interface {
Debugw(msg string, keysAndValues ...any)
Infow(msg string, keysAndValues ...any)
Warnw(msg string, keysAndValues ...any)
Errorw(msg string, keysAndValues ...any)
WithContext(ctx context.Context) Logger
}
Logger defines the logging interface used by the websocket package.
type LoginEvent ¶
LoginEvent represents a user login event.
type Metrics ¶ added in v0.2.0
type Metrics struct {
// Connection metrics
ConnectionsTotal prometheus.Counter
ConnectionsCurrent prometheus.Gauge
AuthenticatedConns prometheus.Gauge
AnonymousConns prometheus.Gauge
// Message metrics
MessagesReceived prometheus.Counter
MessagesSent prometheus.Counter
BroadcastsSent prometheus.Counter
// Error metrics
ErrorsTotal *prometheus.CounterVec
// Subscription metrics
TopicsTotal prometheus.Gauge
SubscriptionsTotal prometheus.Counter
}
Metrics holds all Prometheus metrics for the WebSocket hub.
func NewMetrics ¶ added in v0.2.0
NewMetrics creates a new Metrics instance with default metric definitions.
func (*Metrics) Collectors ¶ added in v0.2.0
func (m *Metrics) Collectors() []prometheus.Collector
Collectors returns all metric collectors for custom registration.
func (*Metrics) MustRegister ¶ added in v0.2.0
func (m *Metrics) MustRegister(reg prometheus.Registerer)
MustRegister registers all metrics and panics on error.
func (*Metrics) Register ¶ added in v0.2.0
func (m *Metrics) Register(reg prometheus.Registerer) error
Register registers all metrics with the given registerer.
type Middleware ¶
Middleware wraps a handler with additional functionality.
func Chain ¶
func Chain(middlewares ...Middleware) Middleware
Chain combines multiple middlewares into a single middleware.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router routes JSON-RPC methods to handlers with middleware.
func (*Router) Group ¶
func (r *Router) Group(middlewares ...Middleware) *Group
Group creates a new handler group with additional middleware.
func (*Router) Handle ¶
func (r *Router) Handle(method string, handler Handler, middlewares ...Middleware)
Handle registers a handler for a method with optional middlewares. Middlewares are applied in order: global -> group -> method-specific.
func (*Router) Use ¶
func (r *Router) Use(middlewares ...Middleware) *Router
Use adds global middleware that applies to all handlers.
type SubscribeEvent ¶
SubscribeEvent represents a topic subscription event.
type TokenParser ¶
TokenParser parses a JWT token and returns user info.
type UnsubscribeEvent ¶
UnsubscribeEvent represents a topic unsubscription event.