Documentation
¶
Index ¶
- func AuthMiddleware(next http.Handler) http.Handler
- func BroadcastToAll(message []byte)
- func BroadcastToRoom(roomName string, message []byte, exclude *Client)
- func ExampleChatServer()
- func ExampleNotificationServer()
- func GetConnectedClients() int
- func GetRoomClients(roomName string) int
- func GetRooms() []string
- func GetTypedMetadata[T any](c *Client, key string) (T, error)
- func RegisterRoutes(router chi.Router, path string)
- func SetDefaultHub(hub *Hub)
- func WSHandler(w http.ResponseWriter, r *http.Request)
- func WithClient(ctx context.Context, client *Client) context.Context
- func WithHub(ctx context.Context, hub *Hub) context.Context
- type ChatMessage
- type Client
- func (c *Client) GetID() string
- func (c *Client) GetMetadata(key string) interface{}
- func (c *Client) GetRooms() []string
- func (c *Client) GetUserID() string
- func (c *Client) Send(message []byte) error
- func (c *Client) SendMessage(msgType string, data interface{}) error
- func (c *Client) SetMetadata(key string, value interface{})
- type Config
- type ContextKey
- type Hub
- func (h *Hub) BroadcastToAll(message []byte)
- func (h *Hub) BroadcastToRoom(roomName string, message []byte, exclude *Client)
- func (h *Hub) GetConnectedClients() int
- func (h *Hub) GetRoomClients(roomName string) int
- func (h *Hub) GetRooms() []string
- func (h *Hub) JoinRoom(client *Client, roomName string)
- func (h *Hub) LeaveRoom(client *Client, roomName string)
- func (h *Hub) Run(ctx context.Context)
- func (h *Hub) ServeWS(w http.ResponseWriter, r *http.Request)
- type Message
- type Module
- func (m *Module) Broadcast(message []byte)
- func (m *Module) BroadcastToRoom(room string, message []byte, exclude *Client)
- func (m *Module) GetClientCount() int
- func (m *Module) Handler() http.HandlerFunc
- func (m *Module) Initialize(g interface{}) error
- func (m *Module) Name() string
- func (m *Module) Shutdown(ctx context.Context) error
- type Option
- func WithAllowedOrigins(origins []string) Option
- func WithAuthenticateConnection(fn func(r *http.Request) (string, error)) Option
- func WithBufferSizes(broadcast, roomMessage, client int) Option
- func WithMaxMessageSize(size int64) Option
- func WithOnConnect(handler func(*Client)) Option
- func WithOnDisconnect(handler func(*Client)) Option
- func WithOnJoinRoom(handler func(*Client, string)) Option
- func WithOnLeaveRoom(handler func(*Client, string)) Option
- func WithOnMessage(handler func(*Client, *Message)) Option
- func WithPongTimeout(timeout time.Duration) Option
- func WithWriteTimeout(timeout time.Duration) Option
- type Room
- type RoomMessage
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func BroadcastToAll ¶
func BroadcastToAll(message []byte)
func BroadcastToRoom ¶
func ExampleChatServer ¶
func ExampleChatServer()
func ExampleNotificationServer ¶
func ExampleNotificationServer()
func GetConnectedClients ¶
func GetConnectedClients() int
func GetRoomClients ¶
func GetTypedMetadata ¶
GetTypedMetadata is a generic helper for type-safe metadata retrieval. Example: userID, err := GetTypedMetadata[int](client, "user_id")
func RegisterRoutes ¶
func SetDefaultHub ¶
func SetDefaultHub(hub *Hub)
Types ¶
type ChatMessage ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
func (*Client) GetMetadata ¶
func (*Client) SendMessage ¶
func (*Client) SetMetadata ¶
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
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 (*Hub) BroadcastToAll ¶
func (*Hub) BroadcastToRoom ¶
func (*Hub) GetConnectedClients ¶
func (*Hub) GetRoomClients ¶
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 ¶
NewModule creates a new WebSocket module with the given configuration options. It uses the same Option functions as NewConfig.
func (*Module) BroadcastToRoom ¶
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 ¶
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 ¶
type Option ¶
type Option func(*Config)
func WithAllowedOrigins ¶
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 ¶
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
})