Go Developer Toolkit
Doc 2 of 2 β’ Series Complete
A curated set of Go libraries and CLI tools for building production-grade applications β covering WebSocket hubs, deployment automation, and database optimization.
go-ws-hub
βZero-dependency WebSocket hub for Go β handles 100k concurrent connectionsβ
A production-ready, zero-dependency Go library implementing the Hub/Client pattern for WebSocket applications. Includes connection lifecycle management, room-based routing, Redis pub/sub backend for horizontal scaling, and a built-in reconnection protocol.
Installation
Requirements
Required
Required only for Redis pub/sub backend (optional for single-instance)
docker run -d -p 6379:6379 redis:7-alpineRun with Redis for multi-instance scaling
Use Docker Compose to run the app and Redis together
Platform Notes
- Set REDIS_URL env var to enable the Redis pub/sub backend
Quick Start
Build a WebSocket chat server in 3 steps
Install go-ws-hub
Add to your Go module
go get github.com/lordofthemind/go-ws-hub@latestπ‘ Tips
- β’Requires Go 1.21+
Create a Hub and register the handler
Create a Hub, start it in a goroutine, and register the WebSocket handler
package main
import (
"net/http"
"github.com/lordofthemind/go-ws-hub"
)
func main() {
hub := wshub.NewHub(wshub.DefaultConfig())
go hub.Run()
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
wshub.ServeWs(hub, w, r)
})
http.ListenAndServe(":8080", nil)
}Send messages programmatically
Broadcast to all clients or to a specific room from application code
// Broadcast to all connected clients
hub.Broadcast([]byte(`{"type":"system","text":"Maintenance in 5 minutes"}`))
// Broadcast to a specific room
hub.BroadcastToRoom("room-42", []byte(`{"type":"chat","text":"Hello room!"}`))
// Get connected client count
count := hub.ClientCount()You're all set! Check out the detailed usage guide below for more advanced features.
Usage Guide
In-memory Hub (single instance)
Default configuration β no Redis required
hub := wshub.NewHub(wshub.DefaultConfig())
go hub.Run()
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
wshub.ServeWs(hub, w, r)
})Room-based broadcasting
Join clients to rooms and broadcast to specific rooms
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
clientID := r.URL.Query().Get("userId")
room := r.URL.Query().Get("room")
wshub.ServeWs(hub, w, r, wshub.ClientOptions{
ID: clientID,
Room: room,
})
})
// Broadcast to a specific room later
hub.BroadcastToRoom("team-engineering", message)API Reference
NewHub
Creates and returns a new Hub with the given configuration.
Signature
NewHub(config Config) *HubParameters
configConfigRequiredHub configuration (backend, timeouts, buffer sizes, middleware)
Returns
*HubExamples
hub := wshub.NewHub(wshub.DefaultConfig())hub := wshub.NewHub(wshub.Config{SendBufferSize: 1024})Hub.Run
Starts the Hub's event loop. Must be called in a goroutine before any clients connect. Blocks until the Hub is stopped.
Signature
func (h *Hub) Run()Returns
void (blocks)Examples
go hub.Run()Hub.Broadcast
Sends a message to all connected clients across all rooms.
Signature
func (h *Hub) Broadcast(message []byte)Parameters
message[]byteRequiredRaw message bytes (typically JSON-encoded)
Returns
voidExamples
hub.Broadcast([]byte(`{"type":"announcement","text":"Server restart in 5m"}`))Hub.BroadcastToRoom
Sends a message to all clients in a specific room.
Signature
func (h *Hub) BroadcastToRoom(room string, message []byte)Parameters
roomstringRequiredRoom identifier
message[]byteRequiredMessage to broadcast
Returns
voidExamples
hub.BroadcastToRoom("room-42", []byte(`{"type":"chat","text":"hi"}`))ServeWs
HTTP handler that upgrades the connection to WebSocket and registers the client with the Hub.
Signature
ServeWs(hub *Hub, w http.ResponseWriter, r *http.Request, opts ...ClientOptions)Parameters
hub*HubRequiredThe hub to register the client with
whttp.ResponseWriterRequiredHTTP response writer
r*http.RequestRequiredHTTP request
opts...ClientOptionsOptional client options (ID, Room, Metadata)
Returns
voidExamples
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) { wshub.ServeWs(hub, w, r) })Examples
Real-world code examples and use cases
Minimal WebSocket echo server
beginnerSimplest possible usage β echo messages back to the sender
hub := wshub.NewHub(wshub.DefaultConfig())
hub.OnMessage(func(msg *wshub.Message) {
hub.SendToClient(msg.ClientID, msg.Data)
})
go hub.Run()
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
wshub.ServeWs(hub, w, r)
})
http.ListenAndServe(":8080", nil)Chat server with room routing
intermediateMulti-room chat where clients join via query param
hub.OnMessage(func(msg *wshub.Message) {
var payload struct {
Type string `json:"type"`
Text string `json:"text"`
}
if err := json.Unmarshal(msg.Data, &payload); err != nil {
return
}
if payload.Type == "chat" {
hub.BroadcastToRoom(msg.Room, msg.Data)
}
})Frequently Asked Questions
3 questions answered
Still have questions?
Check out the source code or open an issue on GitHub
Related Content
Explore related articles, projects, and tools.