websocket

package
v0.0.0-...-0409f2c Latest Latest
Warning

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

Go to latest
Published: Dec 29, 2025 License: MIT Imports: 17 Imported by: 0

Documentation

Index

Constants

View Source
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

func GetConfigSummary(config *Config) map[string]interface{}

GetConfigSummary gets configuration summary

func HandleWebSocket

func HandleWebSocket(hub *Hub, w http.ResponseWriter, r *http.Request, userID string)

HandleWebSocket handles WebSocket connection

func RegisterRoutes

func RegisterRoutes(r *gin.Engine, handler *Handler)

RegisterRoutes registers all routes

func ValidateConfig

func ValidateConfig(config *Config) error

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 CloneConfig

func CloneConfig(config *Config) *Config

CloneConfig clones configuration

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns default configuration

func LoadConfigFromEnv

func LoadConfigFromEnv() *Config

LoadConfigFromEnv loads WebSocket configuration from environment variables

func MergeConfig

func MergeConfig(configs ...*Config) *Config

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

func (c *Connection) Close() error

Close closes the 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 NewHandler

func NewHandler(hub *Hub) *Handler

NewHandler creates a new WebSocket handlers

func (*Handler) BroadcastMessage

func (h *Handler) BroadcastMessage(c *gin.Context)

BroadcastMessage broadcasts a message to all connections

func (*Handler) DisconnectGroup

func (h *Handler) DisconnectGroup(c *gin.Context)

DisconnectGroup disconnects all connections for a specific group

func (*Handler) DisconnectUser

func (h *Handler) DisconnectUser(c *gin.Context)

DisconnectUser disconnects all connections for a specific user

func (*Handler) GetGroupStats

func (h *Handler) GetGroupStats(c *gin.Context)

GetGroupStats gets connection statistics for a specific group

func (*Handler) GetStats

func (h *Handler) GetStats(c *gin.Context)

GetStats gets WebSocket statistics

func (*Handler) GetUserStats

func (h *Handler) GetUserStats(c *gin.Context)

GetUserStats gets connection statistics for a specific user

func (*Handler) HandleAnonymousWebSocket

func (h *Handler) HandleAnonymousWebSocket(c *gin.Context)

HandleAnonymousWebSocket handles anonymous WebSocket connection (optional)

func (*Handler) HandleWebSocket

func (h *Handler) HandleWebSocket(c *gin.Context)

HandleWebSocket handles WebSocket connection request

func (*Handler) HealthCheck

func (h *Handler) HealthCheck(c *gin.Context)

HealthCheck performs WebSocket health check

func (*Handler) SendMessage

func (h *Handler) SendMessage(c *gin.Context)

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 NewHub

func NewHub(config *Config) *Hub

NewHub creates a new Hub instance

func (*Hub) BroadcastToAll

func (h *Hub) BroadcastToAll(message *Message) error

BroadcastToAll broadcasts a message to all connections

func (*Hub) BroadcastToGroup

func (h *Hub) BroadcastToGroup(group string, message *Message) error

BroadcastToGroup broadcasts a message to a specific group

func (*Hub) Close

func (h *Hub) Close()

Close closes the Hub

func (*Hub) GetBroadcastChannel

func (h *Hub) GetBroadcastChannel() chan<- *Message

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

func (h *Hub) GetConnectionCount() int64

GetConnectionCount gets current connection count

func (*Hub) GetGroupConnections

func (h *Hub) GetGroupConnections(group string) int

GetGroupConnections gets connection count for a group

func (*Hub) GetUserConnections

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

GetUserConnections gets connection count for a user

func (*Hub) IsConnectionAlive

func (h *Hub) IsConnectionAlive(connID string) bool

IsConnectionAlive checks if a connection is alive

func (*Hub) SendToUser

func (h *Hub) SendToUser(userID string, message *Message) error

SendToUser sends a message to a specific user

type Message

type Message struct {
	Type      string      `json:"type"`
	Data      interface{} `json:"data"`
	Timestamp int64       `json:"timestamp"`
	From      string      `json:"from,omitempty"`
	To        string      `json:"to,omitempty"`
	Group     string      `json:"group,omitempty"`
}

Message defines WebSocket message structure

Jump to

Keyboard shortcuts

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