websocket

package module
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Aug 5, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AuthMiddleware

func AuthMiddleware(next http.Handler) http.Handler

func BroadcastToAll

func BroadcastToAll(message []byte)

func BroadcastToRoom

func BroadcastToRoom(roomName string, message []byte, exclude *Client)

func ExampleChatServer

func ExampleChatServer()

func ExampleNotificationServer

func ExampleNotificationServer()

func GetConnectedClients

func GetConnectedClients() int

func GetRoomClients

func GetRoomClients(roomName string) int

func GetRooms

func GetRooms() []string

func GetTypedMetadata

func GetTypedMetadata[T any](c *Client, key string) (T, error)

GetTypedMetadata is a generic helper for type-safe metadata retrieval. Example: userID, err := GetTypedMetadata[int](client, "user_id")

func RegisterRoutes

func RegisterRoutes(router chi.Router, path string)

func SetDefaultHub

func SetDefaultHub(hub *Hub)

func WSHandler

func WSHandler(w http.ResponseWriter, r *http.Request)

func WithClient

func WithClient(ctx context.Context, client *Client) context.Context

func WithHub

func WithHub(ctx context.Context, hub *Hub) context.Context

Types

type ChatMessage

type ChatMessage struct {
	Username string    `json:"username"`
	Message  string    `json:"message"`
	Room     string    `json:"room"`
	Time     time.Time `json:"time"`
}

type Client

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

func GetClient

func GetClient(ctx context.Context) (*Client, bool)

func (*Client) GetID

func (c *Client) GetID() string

func (*Client) GetMetadata

func (c *Client) GetMetadata(key string) interface{}

func (*Client) GetRooms

func (c *Client) GetRooms() []string

func (*Client) GetUserID

func (c *Client) GetUserID() string

func (*Client) Send

func (c *Client) Send(message []byte) error

func (*Client) SendMessage

func (c *Client) SendMessage(msgType string, data interface{}) error

func (*Client) SetMetadata

func (c *Client) SetMetadata(key string, value interface{})

type Config

type Config struct {
	WriteWait         time.Duration
	PongWait          time.Duration
	PingPeriod        time.Duration
	MaxMessageSize    int64
	BroadcastBuffer   int
	RoomMessageBuffer int
	ClientBuffer      int
	AllowedOrigins    []string // List of allowed origins for WebSocket connections

	// AuthenticateConnection validates the WebSocket connection and returns a verified user ID.
	// If nil, connections are treated as anonymous with auto-generated IDs.
	// IMPORTANT: Never trust client-provided headers for user identity - always validate
	// using session cookies, JWT tokens, or other secure authentication mechanisms.
	AuthenticateConnection func(r *http.Request) (userID string, err error)

	OnConnect    func(*Client)
	OnDisconnect func(*Client)
	OnMessage    func(*Client, *Message)
	OnJoinRoom   func(*Client, string)
	OnLeaveRoom  func(*Client, string)
}

func DefaultConfig

func DefaultConfig() *Config

func NewConfig

func NewConfig(options ...Option) *Config

type ContextKey

type ContextKey string
const (
	ClientContextKey ContextKey = "websocket_client"
	HubContextKey    ContextKey = "websocket_hub"
)

type Hub

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

func GetDefaultHub

func GetDefaultHub() *Hub

func GetHub

func GetHub(ctx context.Context) (*Hub, bool)

func NewHub

func NewHub(config *Config) *Hub

func (*Hub) BroadcastToAll

func (h *Hub) BroadcastToAll(message []byte)

func (*Hub) BroadcastToRoom

func (h *Hub) BroadcastToRoom(roomName string, message []byte, exclude *Client)

func (*Hub) GetConnectedClients

func (h *Hub) GetConnectedClients() int

func (*Hub) GetRoomClients

func (h *Hub) GetRoomClients(roomName string) int

func (*Hub) GetRooms

func (h *Hub) GetRooms() []string

func (*Hub) JoinRoom

func (h *Hub) JoinRoom(client *Client, roomName string)

func (*Hub) LeaveRoom

func (h *Hub) LeaveRoom(client *Client, roomName string)

func (*Hub) Run

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

func (*Hub) ServeWS

func (h *Hub) ServeWS(w http.ResponseWriter, r *http.Request)

type Message

type Message struct {
	Type      string                 `json:"type"`
	Data      interface{}            `json:"data,omitempty"`
	Room      string                 `json:"room,omitempty"`
	UserID    string                 `json:"user_id,omitempty"`
	Timestamp time.Time              `json:"timestamp"`
	Metadata  map[string]interface{} `json:"metadata,omitempty"`
}

type Module

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

Module implements the tjo.Module interface for WebSocket functionality. Use this to opt-in to WebSocket support in your application.

Example:

app := tjo.Tjo{}
app.New(rootPath, websocket.NewModule(
    websocket.WithAllowedOrigins([]string{"https://example.com"}),
    websocket.WithAuthenticateConnection(myAuthFunc),
))

// Later, use the hub:
if wsModule := app.Modules.Get("websocket"); wsModule != nil {
    hub := wsModule.(*websocket.Module).Hub
    hub.Broadcast([]byte("Hello everyone!"))
}

func NewModule

func NewModule(opts ...Option) *Module

NewModule creates a new WebSocket module with the given configuration options. It uses the same Option functions as NewConfig.

func (*Module) Broadcast

func (m *Module) Broadcast(message []byte)

Broadcast sends a message to all connected clients

func (*Module) BroadcastToRoom

func (m *Module) BroadcastToRoom(room string, message []byte, exclude *Client)

BroadcastToRoom sends a message to all clients in a room. Use exclude to exclude a specific client (e.g., the sender), or nil to include all.

func (*Module) GetClientCount

func (m *Module) GetClientCount() int

GetClientCount returns the number of connected clients

func (*Module) Handler

func (m *Module) Handler() http.HandlerFunc

Handler returns an HTTP handler for WebSocket connections. Mount this at your desired path (e.g., "/ws").

func (*Module) Initialize

func (m *Module) Initialize(g interface{}) error

func (*Module) Name

func (m *Module) Name() string

Name returns the module identifier

func (*Module) Shutdown

func (m *Module) Shutdown(ctx context.Context) error

Shutdown gracefully stops the WebSocket hub. This closes all connections and waits for the hub to finish.

type Option

type Option func(*Config)

func WithAllowedOrigins

func WithAllowedOrigins(origins []string) Option

WithAllowedOrigins sets the allowed origins for WebSocket connections. If empty, all origins are rejected (secure default). Use []string{"*"} to allow all origins (not recommended for production).

func WithAuthenticateConnection

func WithAuthenticateConnection(fn func(r *http.Request) (string, error)) Option

WithAuthenticateConnection sets the authentication callback for WebSocket connections. The callback should validate the request (e.g., check JWT token, session cookie) and return a verified user ID. If authentication fails, return an error.

Example with JWT:

WithAuthenticateConnection(func(r *http.Request) (string, error) {
    token := r.Header.Get("Authorization")
    claims, err := auth.ValidateJWT(strings.TrimPrefix(token, "Bearer "))
    if err != nil {
        return "", err
    }
    return claims.UserID, nil
})

Example with session:

WithAuthenticateConnection(func(r *http.Request) (string, error) {
    session := sessionManager.Get(r.Context())
    userID := session.GetString("user_id")
    if userID == "" {
        return "", errors.New("not authenticated")
    }
    return userID, nil
})

func WithBufferSizes

func WithBufferSizes(broadcast, roomMessage, client int) Option

func WithMaxMessageSize

func WithMaxMessageSize(size int64) Option

func WithOnConnect

func WithOnConnect(handler func(*Client)) Option

func WithOnDisconnect

func WithOnDisconnect(handler func(*Client)) Option

func WithOnJoinRoom

func WithOnJoinRoom(handler func(*Client, string)) Option

func WithOnLeaveRoom

func WithOnLeaveRoom(handler func(*Client, string)) Option

func WithOnMessage

func WithOnMessage(handler func(*Client, *Message)) Option

func WithPongTimeout

func WithPongTimeout(timeout time.Duration) Option

func WithWriteTimeout

func WithWriteTimeout(timeout time.Duration) Option

type Room

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

type RoomMessage

type RoomMessage struct {
	Room    string
	Message []byte
	Exclude *Client
}

Jump to

Keyboard shortcuts

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