websocket

package module
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Dec 28, 2025 License: Apache-2.0 Imports: 12 Imported by: 0

README

WebSocket

Go Reference Go Report Card CI

A production-ready WebSocket framework for Go using JSON-RPC 2.0 protocol with middleware support, grouped routing, and connection management. Part of the Bingo ecosystem.

📖 Documentation: bingoctl.dev/en/advanced/websocket

中文文档

Features

  • JSON-RPC 2.0 Protocol - Industry-standard message format (used by MCP, Ethereum, VSCode LSP)
  • Middleware Pattern - Familiar programming model like Gin/Echo
  • Grouped Routing - Support public/private groups with different middleware chains
  • Connection Management - Hub for client registration, authentication, and topic subscriptions
  • Built-in Handlers - Heartbeat, subscribe/unsubscribe out of the box
  • Rate Limiting - Token bucket algorithm with per-method configuration
  • Single Device Login - Automatic session kick when same user logs in from another device
  • Prometheus Metrics - Built-in observability with connection, message, and error metrics
  • Connection Limits - Configurable total and per-user connection limits
  • Graceful Shutdown - Clean shutdown with client notification

Installation

go get github.com/bingo-project/websocket

Quick Start

package main

import (
    "context"
    "log"
    "net/http"

    "github.com/bingo-project/websocket"
    "github.com/bingo-project/websocket/jsonrpc"
    "github.com/bingo-project/websocket/middleware"
    gorillaWS "github.com/gorilla/websocket"
)

func main() {
    // Create hub and router
    hub := websocket.NewHub()
    router := websocket.NewRouter()

    // Add global middleware
    router.Use(
        middleware.Recovery,
        middleware.RequestID,
        middleware.Logger,
    )

    // Public methods (no auth required)
    public := router.Group()
    public.Handle("heartbeat", websocket.HeartbeatHandler)
    public.Handle("echo", func(c *websocket.Context) *jsonrpc.Response {
        return c.JSON(c.Request.Params)
    })

    // Private methods (require auth)
    private := router.Group(middleware.Auth)
    private.Handle("subscribe", websocket.SubscribeHandler)

    // Start hub
    ctx, cancel := context.WithCancel(context.Background())
    defer cancel()
    go hub.Run(ctx)

    // WebSocket upgrader
    upgrader := gorillaWS.Upgrader{
        CheckOrigin: func(r *http.Request) bool { return true },
    }

    // HTTP handler
    http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
        conn, err := upgrader.Upgrade(w, r, nil)
        if err != nil {
            return
        }

        client := websocket.NewClient(hub, conn, context.Background(),
            websocket.WithRouter(router),
        )
        hub.Register <- client

        go client.WritePump()
        go client.ReadPump()
    })

    log.Println("Server starting on :8080")
    log.Fatal(http.ListenAndServe(":8080", nil))
}

Message Format

Request
{
    "jsonrpc": "2.0",
    "method": "auth.login",
    "params": {"username": "test", "password": "123456"},
    "id": 1
}
Success Response
{
    "jsonrpc": "2.0",
    "result": {"token": "xxx", "expiresAt": 1234567890},
    "id": 1
}
Error Response
{
    "jsonrpc": "2.0",
    "error": {
        "code": -32001,
        "reason": "Unauthorized",
        "message": "Login required"
    },
    "id": 1
}
Server Push (Notification)
{
    "jsonrpc": "2.0",
    "method": "session.kicked",
    "params": {"reason": "Account logged in elsewhere"}
}

Middleware

Built-in Middleware
Middleware Description
Recovery / RecoveryWithLogger Catch panics, return 500 error
RequestID Inject request-id into context
Logger / LoggerWithLogger Log requests and latency
Auth Verify user is authenticated
RateLimit / RateLimitWithStore Token bucket rate limiting
LoginStateUpdater Update client state after login
Custom Middleware
func MyMiddleware(next websocket.Handler) websocket.Handler {
    return func(c *websocket.Context) *jsonrpc.Response {
        // Before handler
        log.Printf("Method: %s", c.Method)

        resp := next(c)

        // After handler
        return resp
    }
}

router.Use(MyMiddleware)

Handler

func Login(c *websocket.Context) *jsonrpc.Response {
    var req LoginRequest
    if err := c.BindValidate(&req); err != nil {
        return c.Error(errors.New(400, "InvalidParams", err.Error()))
    }

    // Business logic...
    token := authenticate(req.Username, req.Password)

    // Update client login state
    c.Client.NotifyLogin(userID, req.Platform, tokenExpiresAt)

    return c.JSON(map[string]any{
        "token":     token,
        "expiresAt": tokenExpiresAt,
    })
}

Connection Management

Hub API
// Get client by ID
client := hub.GetClient("client-id")

// Get all clients for a user
clients := hub.GetClientsByUser("user-123")

// Kick client
hub.KickClient("client-id", "reason")

// Kick all sessions of a user
hub.KickUser("user-123", "account suspended")

// Get statistics
stats := hub.Stats()
Push Messages
// Push to specific user on specific platform
hub.PushToUser("ios", "user-123", "order.created", data)

// Push to user on all platforms
hub.PushToUserAllPlatforms("user-123", "security.alert", data)

// Push to topic subscribers
hub.PushToTopic("group:123", "message.new", data)

// Broadcast to all authenticated clients
hub.Broadcast <- message
Topic Subscription
// Client subscribes to topics
hub.Subscribe <- &websocket.SubscribeEvent{
    Client: client,
    Topics: []string{"group:123", "room:lobby"},
    Result: resultChan,
}

// Client unsubscribes
hub.Unsubscribe <- &websocket.UnsubscribeEvent{
    Client: client,
    Topics: []string{"group:123"},
}

Rate Limiting

store := middleware.NewRateLimiterStore()

router.Use(middleware.RateLimitWithStore(&middleware.RateLimitConfig{
    Default: 10, // 10 requests/second
    Methods: map[string]float64{
        "heartbeat": 0,  // No limit
        "subscribe": 5,  // 5 requests/second
    },
}, store))

// Clean up when client disconnects
hub := websocket.NewHub(
    websocket.WithClientDisconnectCallback(store.Remove),
)

Configuration

cfg := &websocket.HubConfig{
    AnonymousTimeout: 10 * time.Second,  // Disconnect if not logged in within 10s
    AnonymousCleanup: 2 * time.Second,   // Cleanup interval
    HeartbeatTimeout: 60 * time.Second,  // No heartbeat for 60s -> disconnect
    HeartbeatCleanup: 30 * time.Second,
    PingPeriod:       54 * time.Second,  // WebSocket ping interval
    PongWait:         60 * time.Second,
    MaxMessageSize:   4096,
    WriteWait:        10 * time.Second,
    MaxConnections:   10000,             // Max total connections (0 = unlimited)
    MaxConnsPerUser:  5,                 // Max connections per user (0 = unlimited)
}

// Validate config before use
if err := cfg.Validate(); err != nil {
    log.Fatal(err)
}

hub := websocket.NewHubWithConfig(cfg)

Prometheus Metrics

import "github.com/prometheus/client_golang/prometheus"

// Create and register metrics
metrics := websocket.NewMetrics("myapp", "websocket")
metrics.MustRegister(prometheus.DefaultRegisterer)

// Attach metrics to hub
hub := websocket.NewHub(websocket.WithMetrics(metrics))

// Available metrics:
// - myapp_websocket_connections_total
// - myapp_websocket_connections_current
// - myapp_websocket_connections_authenticated
// - myapp_websocket_connections_anonymous
// - myapp_websocket_messages_sent_total
// - myapp_websocket_broadcasts_total
// - myapp_websocket_errors_total{type="connection_limit|user_limit|..."}
// - myapp_websocket_topics_current
// - myapp_websocket_subscriptions_total

Connection Limits

// Check before accepting connection (optional, for early rejection)
if !hub.CanAcceptConnection() {
    http.Error(w, "Too many connections", http.StatusServiceUnavailable)
    return
}

// Check before login (optional)
if !hub.CanUserConnect(userID) {
    return c.Error(errors.New(429, "TooManyConnections", "Max connections reached"))
}

// Limits are also enforced automatically in hub

Graceful Shutdown

ctx, cancel := context.WithCancel(context.Background())
go hub.Run(ctx)

// Handle shutdown signal
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
<-sigCh

// Cancel context to trigger graceful shutdown
// Hub will notify all clients before closing
cancel()

Examples

See examples/basic for a complete working example with:

  • Hub configuration and validation
  • Prometheus metrics integration
  • Rate limiting middleware
  • Public and private route groups
  • Connection limits
  • Graceful shutdown

Error Code Mapping

HTTP Status JSON-RPC Code Description
400 -32602 Invalid params
401 -32001 Unauthorized
403 -32003 Permission denied
404 -32004 Not found
429 -32029 Too many requests
500 -32603 Internal error

Performance

Benchmark Results

Tested on Apple M1 Pro:

Operation Latency Allocations
Broadcast (1000 clients) ~1.7μs 0 allocs
Subscribe ~1.3μs 10 allocs
PushToTopic (100 clients) ~6.3μs 7 allocs
Register/Unregister ~2.8μs 9 allocs

Run benchmarks:

go test -bench=. -benchmem ./...
Capacity Estimation

Based on gorilla/websocket and Go runtime characteristics, single-server capacity is primarily memory-bound:

Server Config Estimated Connections Notes
4 cores, 8GB 10,000 - 30,000 Dev/test
8 cores, 16GB 50,000 - 100,000 Production entry
16 cores, 32GB 100,000 - 200,000 Mid-size production
32 cores, 64GB 200,000 - 500,000 Large-scale production

Memory estimate: ~20-30KB per connection (2 goroutines, read/write buffers, application data)

Use Cases

Recommended:

  • Instant messaging (IM)
  • Real-time notifications
  • Online collaboration (docs, whiteboard)
  • Live data display (stocks, monitoring)
  • Game state synchronization

⚠️ Requires additional optimization:

  • Ultra-large scale (1M+ connections): Consider async I/O libraries like gnet or nbio
  • Ultra-high frequency (100K+ msg/s): Consider message batching and compression
Production Tuning
Linux Kernel Parameters
# /etc/sysctl.conf

# Increase file descriptor limit
fs.file-max = 1000000

# TCP connection optimization
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.core.netdev_max_backlog = 65535

# Memory optimization
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
Process Limits
# /etc/security/limits.conf
* soft nofile 1000000
* hard nofile 1000000

License

Apache License 2.0

Documentation

Index

Constants

View Source
const (
	PlatformWeb     = "web"
	PlatformIOS     = "ios"
	PlatformAndroid = "android"
	PlatformH5      = "h5"
	PlatformMiniApp = "miniapp"
	PlatformDesktop = "desktop"
)

Platform constants.

Variables

View Source
var FromError = errors.FromError

FromError converts an error to *Error.

View Source
var NewError = errors.New

NewError creates a new Error with the given code, reason, and formatted message.

Functions

func HeartbeatHandler

func HeartbeatHandler(c *Context) *jsonrpc.Response

HeartbeatHandler responds to heartbeat requests.

func IsValidPlatform

func IsValidPlatform(p string) bool

IsValidPlatform checks if the platform string is valid.

func RequestID

func RequestID(ctx context.Context) string

RequestID retrieves the request ID from the context.

func SubscribeHandler

func SubscribeHandler(c *Context) *jsonrpc.Response

SubscribeHandler handles topic subscription.

func TokenLoginHandler added in v0.2.2

func TokenLoginHandler(c *Context) *jsonrpc.Response

TokenLoginHandler handles token-based authentication. It validates the provided access token and updates client state. Use with LoginStateUpdater middleware to complete the login process.

func UnsubscribeHandler

func UnsubscribeHandler(c *Context) *jsonrpc.Response

UnsubscribeHandler handles topic unsubscription.

func UserID

func UserID(ctx context.Context) string

UserID retrieves the user ID from the context.

func WithRequestID

func WithRequestID(ctx context.Context, requestID string) context.Context

WithRequestID stores the request ID in the context.

func WithUserID

func WithUserID(ctx context.Context, userID string) context.Context

WithUserID stores the user 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 NewClient

func NewClient(hub *Hub, conn *websocket.Conn, ctx context.Context, opts ...ClientOption) *Client

NewClient creates a new WebSocket client.

func (*Client) GetPlatform added in v0.2.1

func (c *Client) GetPlatform() string

GetPlatform returns the platform (thread-safe).

func (*Client) GetUserID added in v0.2.1

func (c *Client) GetUserID() string

GetUserID returns the user ID (thread-safe).

func (*Client) Heartbeat

func (c *Client) Heartbeat(currentTime int64)

Heartbeat updates the heartbeat time.

func (*Client) HeartbeatTime

func (c *Client) HeartbeatTime() int64

HeartbeatTime returns the last heartbeat time.

func (*Client) IsAuthenticated

func (c *Client) IsAuthenticated() bool

IsAuthenticated returns true if the client has logged in.

func (*Client) IsHeartbeatTimeout

func (c *Client) IsHeartbeatTimeout(currentTime int64) bool

IsHeartbeatTimeout returns true if heartbeat has timed out.

func (*Client) Login

func (c *Client) Login(platform, userID string, loginTime int64)

Login sets the user info for this client.

func (*Client) NotifyLogin

func (c *Client) NotifyLogin(userID, platform string, tokenExpiresAt int64)

NotifyLogin sends a login event to the hub.

func (*Client) ParseToken

func (c *Client) ParseToken(token string) (*TokenInfo, error)

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) SendJSON

func (c *Client) SendJSON(v any)

SendJSON sends a JSON message to the client.

func (*Client) UpdateContext

func (c *Client) UpdateContext(userID string)

UpdateContext updates the client context with user info.

func (*Client) WritePump

func (c *Client) WritePump()

WritePump pumps messages from the hub to the websocket connection.

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 WithRouter

func WithRouter(r *Router) ClientOption

WithRouter sets a router 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
	// contains filtered or unexported fields
}

Context contains all information needed by middleware. It embeds context.Context so it can be passed directly to business layer methods.

func (*Context) BindParams

func (c *Context) BindParams(v any) error

BindParams unmarshals the request params into the given struct.

func (*Context) BindValidate

func (c *Context) BindValidate(v any) error

BindValidate unmarshals and validates the request params.

func (*Context) Error

func (c *Context) Error(err error) *jsonrpc.Response

Error returns a JSON-RPC error response.

func (*Context) JSON

func (c *Context) JSON(data any) *jsonrpc.Response

JSON returns a successful JSON-RPC response with the given data.

func (*Context) LoginInfo added in v0.2.2

func (c *Context) LoginInfo() *LoginInfo

LoginInfo returns the login information set by handler.

func (*Context) RequestID

func (c *Context) RequestID() string

RequestID returns the request ID from context.

func (*Context) SetLoginInfo added in v0.2.2

func (c *Context) SetLoginInfo(tokenInfo *TokenInfo, platform string)

SetLoginInfo stores login information for middleware to process.

func (*Context) UserID

func (c *Context) UserID() string

UserID returns the user ID from context.

type ContextUpdater

type ContextUpdater func(ctx context.Context, userID string) context.Context

ContextUpdater updates the client context with user info after login.

type Error

type Error = errors.Error

Error is an alias for errors.Error.

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 Handler

type Handler func(*Context) *jsonrpc.Response

Handler is a message handler function.

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 NewHub

func NewHub(opts ...HubOption) *Hub

NewHub creates a new Hub with default config.

func NewHubWithConfig

func NewHubWithConfig(cfg *HubConfig, opts ...HubOption) *Hub

NewHubWithConfig creates a new Hub with custom config.

func (*Hub) AnonymousCount

func (h *Hub) AnonymousCount() int

AnonymousCount returns the number of anonymous connections.

func (*Hub) CanAcceptConnection added in v0.2.0

func (h *Hub) CanAcceptConnection() bool

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

func (h *Hub) CanUserConnect(userID string) bool

CanUserConnect returns true if the user can establish another connection. Returns false if MaxConnsPerUser limit would be exceeded.

func (*Hub) ClientCount

func (h *Hub) ClientCount() int

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) GetClient

func (h *Hub) GetClient(clientID string) *Client

GetClient returns a client by ID.

func (*Hub) GetClientsByUser

func (h *Hub) GetClientsByUser(userID string) []*Client

GetClientsByUser returns all clients for a user across all platforms.

func (*Hub) GetUserClient

func (h *Hub) GetUserClient(platform, userID string) *Client

GetUserClient returns the client for a user.

func (*Hub) KickClient

func (h *Hub) KickClient(clientID string, reason string) bool

KickClient disconnects a client by ID.

func (*Hub) KickUser

func (h *Hub) KickUser(userID string, reason string) int

KickUser disconnects all clients for a user.

func (*Hub) Metrics added in v0.2.0

func (h *Hub) Metrics() *Metrics

Metrics returns the hub's metrics, or nil if not configured.

func (*Hub) PushToTopic

func (h *Hub) PushToTopic(topic, method string, data any)

PushToTopic sends a message to all subscribers of a topic.

func (*Hub) PushToUser

func (h *Hub) PushToUser(platform, userID, method string, data any)

PushToUser sends a message to a specific user on a specific platform.

func (*Hub) PushToUserAllPlatforms

func (h *Hub) PushToUserAllPlatforms(userID, method string, data any)

PushToUserAllPlatforms sends a message to a user on all connected platforms.

func (*Hub) Run

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

Run starts the hub's event loop. It blocks until context is canceled.

func (*Hub) Stats

func (h *Hub) Stats() *HubStats

Stats returns current hub statistics.

func (*Hub) TopicCount

func (h *Hub) TopicCount() int

TopicCount returns the number of topics with subscribers.

func (*Hub) TotalConnections added in v0.2.0

func (h *Hub) TotalConnections() int

TotalConnections returns the total number of connections (anonymous + authenticated).

func (*Hub) UserConnectionCount added in v0.2.0

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

UserConnectionCount returns the number of connections for a user across all platforms.

func (*Hub) UserCount

func (h *Hub) UserCount() int

UserCount returns the number of logged-in users.

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.

func (*HubConfig) Validate added in v0.2.0

func (c *HubConfig) Validate() error

Validate checks if the config values are valid.

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 WithLogger

func WithLogger(l Logger) HubOption

WithLogger sets a custom logger for the hub.

func WithMetrics added in v0.2.0

func WithMetrics(m *Metrics) HubOption

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.

func NopLogger

func NopLogger() Logger

NopLogger returns a logger that discards all output. This is the default logger used when no logger is provided.

type LoginEvent

type LoginEvent struct {
	Client         *Client
	UserID         string
	Platform       string
	TokenExpiresAt int64
}

LoginEvent represents a user login event.

type LoginInfo added in v0.2.2

type LoginInfo struct {
	TokenInfo *TokenInfo
	Platform  string
}

LoginInfo contains login authentication information. Used to pass login state from handler to middleware.

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

func NewMetrics(namespace, subsystem string) *Metrics

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

type Middleware func(Handler) Handler

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 NewRouter

func NewRouter() *Router

NewRouter creates a new Router.

func (*Router) Dispatch

func (r *Router) Dispatch(c *Context) *jsonrpc.Response

Dispatch routes a request to its handler.

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) Methods

func (r *Router) Methods() []string

Methods returns all registered method names.

func (*Router) Use

func (r *Router) Use(middlewares ...Middleware) *Router

Use adds global middleware that applies to all handlers.

type SubscribeEvent

type SubscribeEvent struct {
	Client *Client
	Topics []string
	Result chan []string
}

SubscribeEvent represents a topic subscription event.

type TokenInfo

type TokenInfo struct {
	UserID    string
	ExpiresAt int64
}

TokenInfo contains parsed token information.

type TokenParser

type TokenParser func(token string) (*TokenInfo, error)

TokenParser parses a JWT token and returns user info.

type UnsubscribeEvent

type UnsubscribeEvent struct {
	Client *Client
	Topics []string
}

UnsubscribeEvent represents a topic unsubscription event.

Directories

Path Synopsis
examples
basic command

Jump to

Keyboard shortcuts

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