example-websocket

command
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2025 License: MIT Imports: 7 Imported by: 0

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

  1. Authentication: Validate JWT tokens in middleware
  2. Rate Limiting: Prevent message flooding
  3. Horizontal Scaling: Use Redis for pub/sub across instances
  4. Monitoring: Track connection counts and message rates
  5. Message Size: Enforce max message size limits
  6. Connection Limits: Set max connections per IP
  7. Heartbeat: Configure appropriate ping/pong intervals
  8. 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

The Go Gopher

There is no documentation for this package.

Jump to

Keyboard shortcuts

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