WebSocket
Real-time WebSocket connections with rooms and broadcasting.
RapidGo provides WebSocket support with two approaches: a simple upgrader for basic connections, and a Hub for managing rooms and broadcasting.
Simple WebSocket
For basic WebSocket connections:
import ws "github.com/RAiWorks/RapidGo/v2/core/websocket"
// Echo handler (built-in) — echoes messages back
r.Get("/ws/echo", ws.Upgrader(ws.Echo, nil))
// Custom handler
r.Get("/ws/chat", ws.Upgrader(func(conn *websocket.Conn, ctx context.Context) {
for {
msgType, msg, err := conn.Read(ctx)
if err != nil {
return
}
// Process message...
conn.Write(ctx, msgType, response)
}
}, &ws.Options{
OriginPatterns: []string{"example.com"},
}))
Hub (Rooms and Broadcasting)
The Hub manages multiple clients with room-based messaging:
hub := ws.NewHub()
r.Get("/ws", hub.Handler(func(client *ws.Client) {
// Client connected — client.ID is a unique UUID
hub.Join(client, "general")
for {
msgType, msg, err := client.Conn.Read(context.Background())
if err != nil {
return // Client disconnected — auto-removed from Hub
}
// Broadcast to everyone in the room
hub.Broadcast("general", msgType, msg)
// Broadcast to everyone except sender
hub.BroadcastOthers("general", client, msgType, msg)
}
}))
Hub API
| Method | Description |
|---|---|
NewHub() |
Create a new Hub |
hub.Handler(onConnect) |
Gin handler that upgrades and registers clients |
hub.Join(client, room) |
Add client to a room |
hub.Leave(client, room) |
Remove client from a room |
hub.Broadcast(room, type, data) |
Send to all clients in a room |
hub.BroadcastOthers(room, sender, type, data) |
Send to all except sender |
hub.Send(clientID, type, data) |
Send to a specific client by ID |
hub.Remove(client) |
Remove client from all rooms |
hub.Clients(room) |
List clients in a room |
hub.Rooms() |
List all active rooms |
WebSocket Options
type Options struct {
OriginPatterns []string // Allowed origins for CORS
InsecureSkipVerify bool // Skip origin check (dev only)
}
When opts is nil, all origins are accepted (equivalent to InsecureSkipVerify: true).
Uses the coder/websocket library (formerly nhooyr/websocket).