README
¶
Mithril WebSocket Example
This example demonstrates real-time WebSocket communication with the Mithril framework.
Features Demonstrated
- WebSocket server with connection management
- Room/channel support for grouped messaging
- Broadcasting to all clients
- Room-specific broadcasting
- Client authentication middleware
- Auto-reconnection handling
- Heartbeat/ping-pong
- HTML test client included
Running the Example
# Start the WebSocket server
go run example-websocket/main.go
The server will start on http://localhost:3004.
Testing
1. Using the Web Client
Open your browser to:
http://localhost:3004/client
This provides an interactive HTML client where you can:
- Connect to the WebSocket server
- Join rooms
- Send messages
- Receive broadcasts
2. Using the REST API
Get Server Stats
curl http://localhost:3004/stats
Broadcast to All Clients
curl -X POST http://localhost:3004/broadcast \
-H "Content-Type: application/json" \
-d '{"message":"Hello everyone!"}'
Send to Specific Room
curl -X POST http://localhost:3004/room/general \
-H "Content-Type: application/json" \
-d '{"message":"Hello room members!"}'
3. Using WebSocket Client (JavaScript)
const ws = new WebSocket('ws://localhost:3004/ws');
ws.onopen = () => {
console.log('Connected');
// Join a room
ws.send(JSON.stringify({
type: 'join',
data: 'general'
}));
// Send a message
ws.send(JSON.stringify({
type: 'chat',
room: 'general',
data: 'Hello from JavaScript!'
}));
};
ws.onmessage = (event) => {
const message = JSON.parse(event.data);
console.log('Received:', message);
};
Message Types
Client to Server
Join Room
{
"type": "join",
"data": "room-name"
}
Leave Room
{
"type": "leave",
"data": "room-name"
}
Send Chat Message
{
"type": "chat",
"room": "room-name",
"data": "Your message here"
}
Ping
{
"type": "ping",
"data": "ping"
}
Server to Client
System Message
{
"type": "system",
"data": {
"message": "Server heartbeat",
"time": "2025-10-20T16:23:25+03:30",
"clients": 5
},
"timestamp": "2025-10-20T16:23:25+03:30"
}
Broadcast Message
{
"type": "broadcast",
"data": "Hello everyone!",
"from": "20251020162325-abc123",
"timestamp": "2025-10-20T16:23:25+03:30"
}
Room Message
{
"type": "room_message",
"room": "general",
"data": "Hello room!",
"from": "20251020162325-abc123",
"timestamp": "2025-10-20T16:23:25+03:30"
}
Configuration
Configure WebSocket via environment variables:
WEBSOCKET_ENABLED=true
WEBSOCKET_PORT=8080
WEBSOCKET_PATH=/ws
WEBSOCKET_READ_BUFFER=1024
WEBSOCKET_WRITE_BUFFER=1024
WEBSOCKET_MAX_MESSAGE_SIZE=524288
WEBSOCKET_PING_INTERVAL=54
WEBSOCKET_PONG_TIMEOUT=60
Server API
Create WebSocket Server
import "github.com/mithril-framework/mithril/pkg/websocket"
server := websocket.NewServer()
Add Middleware
server.Use(func(client *websocket.Client) error {
// Authenticate client
token := client.Metadata["token"]
if !validateToken(token) {
return errors.New("unauthorized")
}
return nil
})
Start Server
ctx := context.Background()
go server.Run(ctx)
Broadcast Messages
// To all clients
server.Broadcast(&websocket.Message{
Type: "notification",
Data: "Server maintenance in 5 minutes",
})
// To specific room
server.BroadcastToRoom("admins", &websocket.Message{
Type: "alert",
Data: "Admin notification",
})
// To specific client
server.SendToClient(clientID, &websocket.Message{
Type: "personal",
Data: "Private message",
})
Get Server Stats
clientCount := server.GetClientCount()
roomCount := server.GetRoomCount()
clients := server.GetClients()
roomClients := server.GetRoomClients("general")
Use Cases
- Chat Applications: Real-time messaging
- Live Dashboards: Real-time data updates
- Collaborative Tools: Multi-user editing
- Notifications: Push notifications
- Gaming: Multiplayer games
- IoT: Device communication
- Trading Platforms: Live price updates
- Live Streaming: Chat and interactions
Production Considerations
- Authentication: Validate JWT tokens in middleware
- Rate Limiting: Prevent message flooding
- Horizontal Scaling: Use Redis for pub/sub across instances
- Monitoring: Track connection counts and message rates
- Message Size: Enforce max message size limits
- Connection Limits: Set max connections per IP
- Heartbeat: Configure appropriate ping/pong intervals
- Graceful Shutdown: Close connections cleanly
Next Steps
- Add Redis pub/sub for multi-server deployments
- Implement message persistence
- Add typing indicators
- Implement read receipts
- Add file sharing support
- Create admin dashboard
- Add connection analytics
Documentation
¶
There is no documentation for this package.
Click to show internal directories.
Click to hide internal directories.