Documentation
¶
Index ¶
- Constants
- func GetConfigSummary(config *Config) map[string]interface{}
- func HandleWebSocket(hub *Hub, w http.ResponseWriter, r *http.Request, userID string)
- func RegisterRoutes(r *gin.Engine, handler *Handler)
- func ValidateConfig(config *Config) error
- type Config
- type Connection
- func (c *Connection) Close() error
- func (c *Connection) GetGroups() []string
- func (c *Connection) GetStatus() string
- func (c *Connection) IsInGroup(groupName string) bool
- func (c *Connection) JoinGroup(groupName string)
- func (c *Connection) LeaveGroup(groupName string)
- func (c *Connection) SendError(errorMsg string) error
- func (c *Connection) SendMessage(message *Message) error
- func (c *Connection) SendSuccess(successMsg string) error
- func (c *Connection) SetStatus(status string)
- type Handler
- func (h *Handler) BroadcastMessage(c *gin.Context)
- func (h *Handler) DisconnectGroup(c *gin.Context)
- func (h *Handler) DisconnectUser(c *gin.Context)
- func (h *Handler) GetGroupStats(c *gin.Context)
- func (h *Handler) GetStats(c *gin.Context)
- func (h *Handler) GetUserStats(c *gin.Context)
- func (h *Handler) HandleAnonymousWebSocket(c *gin.Context)
- func (h *Handler) HandleWebSocket(c *gin.Context)
- func (h *Handler) HealthCheck(c *gin.Context)
- func (h *Handler) SendMessage(c *gin.Context)
- type Hub
- func (h *Hub) BroadcastToAll(message *Message) error
- func (h *Hub) BroadcastToGroup(group string, message *Message) error
- func (h *Hub) Close()
- func (h *Hub) GetBroadcastChannel() chan<- *Message
- func (h *Hub) GetConnection(connID string) *Connection
- func (h *Hub) GetConnectionCount() int64
- func (h *Hub) GetGroupConnections(group string) int
- func (h *Hub) GetUserConnections(userID string) int
- func (h *Hub) IsConnectionAlive(connID string) bool
- func (h *Hub) SendToUser(userID string, message *Message) error
- type Message
Constants ¶
const ( // System message types MessageTypePing = "ping" MessageTypePong = "pong" MessageTypeJoinGroup = "join_group" MessageTypeLeaveGroup = "leave_group" MessageTypeGroupJoined = "group_joined" MessageTypeGroupLeft = "group_left" MessageTypeStatus = "status" MessageTypeStatusUpdated = "status_updated" // Business message types MessageTypeChat = "chat" MessageTypeNotification = "notification" MessageTypeSystem = "system" MessageTypeError = "error" MessageTypeSuccess = "success" // Connection status constants ConnectionStatusConnected = "connected" ConnectionStatusDisconnected = "disconnected" ConnectionStatusReconnecting = "reconnecting" ConnectionStatusError = "error" // Default configuration values DefaultMaxConnections = 100000 DefaultHeartbeatInterval = 30 DefaultConnectionTimeout = 60 DefaultMessageBufferSize = 256 DefaultMessageQueueSize = 1000 DefaultReadBufferSize = 1024 DefaultWriteBufferSize = 1024 DefaultMaxMessageSize = 512 // Environment variable configuration keys EnvWebSocketMaxConnections = "WEBSOCKET_MAX_CONNECTIONS" EnvWebSocketHeartbeatInterval = "WEBSOCKET_HEARTBEAT_INTERVAL" EnvWebSocketConnectionTimeout = "WEBSOCKET_CONNECTION_TIMEOUT" EnvWebSocketMessageBufferSize = "WEBSOCKET_MESSAGE_BUFFER_SIZE" EnvWebSocketMessageQueueSize = "WEBSOCKET_MESSAGE_QUEUE_SIZE" EnvWebSocketEnableCompression = "WEBSOCKET_ENABLE_COMPRESSION" EnvWebSocketEnableMessageQueue = "WEBSOCKET_ENABLE_MESSAGE_QUEUE" EnvWebSocketEnableCluster = "WEBSOCKET_ENABLE_CLUSTER" EnvWebSocketClusterNodeID = "WEBSOCKET_CLUSTER_NODE_ID" EnvWebSocketShardCount = "WEBSOCKET_SHARD_COUNT" EnvWebSocketBroadcastWorkers = "WEBSOCKET_BROADCAST_WORKERS" EnvWebSocketDropOnFull = "WEBSOCKET_DROP_ON_FULL" EnvWebSocketCompressionLevel = "WEBSOCKET_COMPRESSION_LEVEL" EnvWebSocketReadBufferSize = "WEBSOCKET_READ_BUFFER_SIZE" EnvWebSocketWriteBufferSize = "WEBSOCKET_WRITE_BUFFER_SIZE" EnvWebSocketMaxMessageSize = "WEBSOCKET_MAX_MESSAGE_SIZE" EnvWebSocketCloseOnBackpressure = "WEBSOCKET_CLOSE_ON_BACKPRESSURE" EnvWebSocketSendTimeoutMs = "WEBSOCKET_SEND_TIMEOUT_MS" EnvWebSocketEnableGlobalPing = "WEBSOCKET_ENABLE_GLOBAL_PING" EnvWebSocketPingWorkers = "WEBSOCKET_PING_WORKERS" // Error messages ErrConnectionLimitExceeded = "connection limit exceeded" ErrInvalidMessageType = "invalid message type" ErrInvalidMessageData = "invalid message data" ErrUserNotFound = "user not found" ErrGroupNotFound = "group not found" ErrConnectionClosed = "connection closed" ErrSendBufferFull = "send buffer full" ErrReadTimeout = "read timeout" ErrWriteTimeout = "write timeout" // Success messages MsgConnectionEstablished = "connection established" MsgMessageSent = "message sent" MsgGroupJoined = "group joined" MsgGroupLeft = "group left" MsgStatusUpdated = "status updated" // Route paths RouteWebSocket = "/ws" RouteWebSocketStats = "/ws/stats" RouteWebSocketHealth = "/ws/health" RouteWebSocketMessage = "/ws/message" RouteWebSocketBroadcast = "/ws/broadcast" RouteWebSocketUser = "/ws/user/:user_id" RouteWebSocketGroup = "/ws/group/:group" )
WebSocket message type constants
Variables ¶
This section is empty.
Functions ¶
func GetConfigSummary ¶
GetConfigSummary gets configuration summary
func HandleWebSocket ¶
HandleWebSocket handles WebSocket connection
func RegisterRoutes ¶
RegisterRoutes registers all routes
func ValidateConfig ¶
ValidateConfig validates WebSocket configuration
Types ¶
type Config ¶
type Config struct {
// Maximum connections
MaxConnections int64
// Heartbeat interval
HeartbeatInterval time.Duration
// Connection timeout
ConnectionTimeout time.Duration
// Message buffer size
MessageBufferSize int
// Read buffer size
ReadBufferSize int
// Write buffer size
WriteBufferSize int
// Maximum message size
MaxMessageSize int
// Whether to enable compression
EnableCompression bool
// Whether to enable message queue
EnableMessageQueue bool
// Message queue size
MessageQueueSize int
// Whether to enable cluster mode
EnableCluster bool
// Cluster node ID
ClusterNodeID string
// Shard count
ShardCount int
// Broadcast worker count
BroadcastWorkerCount int
// Whether to drop when send buffer is full
DropOnFull bool
// Compression level (-2..9)
CompressionLevel int
// Slow consumer strategy: disconnect when backpressure is triggered
CloseOnBackpressure bool
// Send blocking timeout (for non-DropOnFull mode)
SendTimeout time.Duration
// Enable global ping
EnableGlobalPing bool
// Global ping workers
PingWorkerCount int
}
Config is WebSocket configuration
func LoadConfigFromEnv ¶
func LoadConfigFromEnv() *Config
LoadConfigFromEnv loads WebSocket configuration from environment variables
func MergeConfig ¶
MergeConfig merges configurations (later configs override earlier ones)
type Connection ¶
type Connection struct {
ID string
UserID string
Conn *websocket.Conn
Send chan []byte
Hub *Hub
LastPing time.Time
IsAlive bool
Status string // Connection status (ConnectionStatusConnected, ConnectionStatusDisconnected, etc.)
Groups map[string]bool
Metadata map[string]interface{}
// contains filtered or unexported fields
}
Connection represents a WebSocket connection
func (*Connection) GetGroups ¶
func (c *Connection) GetGroups() []string
GetGroups gets all groups the connection belongs to
func (*Connection) GetStatus ¶
func (c *Connection) GetStatus() string
GetStatus gets the connection status
func (*Connection) IsInGroup ¶
func (c *Connection) IsInGroup(groupName string) bool
IsInGroup checks if the connection is in the specified group
func (*Connection) JoinGroup ¶
func (c *Connection) JoinGroup(groupName string)
JoinGroup joins a group
func (*Connection) LeaveGroup ¶
func (c *Connection) LeaveGroup(groupName string)
LeaveGroup leaves a group
func (*Connection) SendError ¶
func (c *Connection) SendError(errorMsg string) error
SendError sends an error message to the connection
func (*Connection) SendMessage ¶
func (c *Connection) SendMessage(message *Message) error
SendMessage sends a message to the current connection
func (*Connection) SendSuccess ¶
func (c *Connection) SendSuccess(successMsg string) error
SendSuccess sends a success message to the connection
func (*Connection) SetStatus ¶
func (c *Connection) SetStatus(status string)
SetStatus sets the connection status
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler is a WebSocket HTTP handlers
func (*Handler) BroadcastMessage ¶
BroadcastMessage broadcasts a message to all connections
func (*Handler) DisconnectGroup ¶
DisconnectGroup disconnects all connections for a specific group
func (*Handler) DisconnectUser ¶
DisconnectUser disconnects all connections for a specific user
func (*Handler) GetGroupStats ¶
GetGroupStats gets connection statistics for a specific group
func (*Handler) GetUserStats ¶
GetUserStats gets connection statistics for a specific user
func (*Handler) HandleAnonymousWebSocket ¶
HandleAnonymousWebSocket handles anonymous WebSocket connection (optional)
func (*Handler) HandleWebSocket ¶
HandleWebSocket handles WebSocket connection request
func (*Handler) HealthCheck ¶
HealthCheck performs WebSocket health check
func (*Handler) SendMessage ¶
SendMessage sends a message to a specific user or group
type Hub ¶
type Hub struct {
// contains filtered or unexported fields
}
Hub manages all WebSocket connections
func (*Hub) BroadcastToAll ¶
BroadcastToAll broadcasts a message to all connections
func (*Hub) BroadcastToGroup ¶
BroadcastToGroup broadcasts a message to a specific group
func (*Hub) GetBroadcastChannel ¶
GetBroadcastChannel gets the broadcast channel (for external message sending)
func (*Hub) GetConnection ¶
func (h *Hub) GetConnection(connID string) *Connection
GetConnection gets a connection by ID
func (*Hub) GetConnectionCount ¶
GetConnectionCount gets current connection count
func (*Hub) GetGroupConnections ¶
GetGroupConnections gets connection count for a group
func (*Hub) GetUserConnections ¶
GetUserConnections gets connection count for a user
func (*Hub) IsConnectionAlive ¶
IsConnectionAlive checks if a connection is alive