1.6 KiB
1.6 KiB
WebSocket Chat - Technical Design
Architecture
Leverages the existing pkg/realtime package which provides:
LocalHub: In-memory connection registry with room supportWSClient: WebSocket connection with heartbeat (ping/pong)Handler: HTTP upgrade and connection lifecycle managementRedisBroadcaster: Cross-pod message distribution via Redis Pub/Sub
Message Flow
Client → WebSocket → WSClient.readPump → Handler.OnMessage callback
→ RedisBroadcaster.Publish → Redis Pub/Sub channel
→ RedisBroadcaster.Run (subscriber) → LocalHub.Broadcast
→ WSClient.writePump → All connected WebSocket clients
Changes Required
1. Configuration (internal/config/config.go)
Add RedisURL field to Config struct, loaded from REDIS_URL environment variable.
2. Main Entry Point (cmd/server/main.go)
- Create Redis client from
REDIS_URL - Create
LocalHuband start its event loop - Create
RedisBroadcasterand start its subscriber loop - Pass hub and broadcaster to
RegisterRoutes - Register shutdown hooks for hub cancellation and Redis client cleanup
3. Route Registration (internal/api/routes.go)
- Accept
realtime.Handleras a parameter - Mount WebSocket handler routes at
/api/chat-api/ws
4. OpenAPI Spec (internal/api/spec.go)
- Add WebSocket tag and endpoint documentation
5. Tests
- Unit test for WebSocket handler wiring
- Integration test for WebSocket connection upgrade and message echo
Dependencies
pkg/realtime(already exists, no changes needed)github.com/redis/go-redis/v9(already in pkg/go.mod)github.com/gorilla/websocket(already in pkg/go.mod)