Documentation
¶
Overview ¶
Use case 03: real-time chat over WebSockets (github.com/coder/websocket).
HTTP is request/response: the server can only talk when asked. WebSocket starts as a normal HTTP request ("Upgrade: websocket"), then the same TCP connection becomes a full-duplex, message-oriented channel where either side can send at any time. That is what chat, live dashboards, multiplayer cursors and notifications need.
Architecture (same hub idea as the TCP chat lesson, now with a browser UI):
browser/Dial <--ws--> handler goroutine (READS) --> hub goroutine --> client.send chan
writer goroutine (WRITES) <--------------------------'
- The hub goroutine owns the set of clients. No mutex: everyone talks to it over channels.
- Each client has a BUFFERED send channel. The hub uses a non-blocking send; if the buffer
is full the client is a slow consumer and is dropped. One slow phone on a bad network
must never slow down a room of 10,000 people. (Alternative: drop the message, not the client.)
- One reader + one writer per connection: the library allows concurrent Write calls but
only ONE goroutine may call Read, and you MUST keep reading or pings/pongs/close frames
are never processed.
Production concerns covered here:
- Origin check: browsers let any web page open a WebSocket to your server, with the user's cookies (cross-site WebSocket hijacking). websocket.Accept rejects requests whose Origin host differs from the request Host unless you list it in AcceptOptions.OriginPatterns. Never use InsecureSkipVerify in production.
- Keepalive: a server-side Ping every N seconds detects dead peers (laptop lid closed, NAT dropped the mapping) and keeps idle connections alive through proxies/load balancers that time out silent connections (nginx defaults to 60s).
- Limits: SetReadLimit caps message size (default 32KiB); we also cap text length.
- Timeouts on every write, so a stalled peer cannot pin a goroutine forever.
- Shutdown: http.Server.Shutdown does NOT close hijacked connections (WebSockets). You must close them yourself. Here a cancelled context makes the hub close every client with the status "going away" (1001) and the browser/client can reconnect elsewhere.
- Escape output in the browser (index.html uses textContent, never innerHTML) to avoid XSS.
Embedded UI: `//go:embed index.html` bakes the HTML into the binary, so deploying is copying one file. embed.FS is read-only and served with http.FileServerFS.
Scaling note: a hub in one process only reaches clients connected to THAT process. With several replicas, publish messages through Redis pub/sub, NATS or Kafka and have every replica fan out to its local clients. Sticky sessions or a connection gateway help too.
Try it:
go run ./08-use-cases/03websocket # demo: in-process websocket.Dial clients go run ./08-use-cases/03websocket -serve :8080 # open http://localhost:8080 in two tabs go run ./08-use-cases/03websocket -serve :8080 -origin chat.example.com # allow another site
In industry: Discord, Slack and Figma-style products keep millions of long-lived connections open (Discord's gateway is famously Elixir/Rust/Go-heavy). In Go, coder/websocket (formerly nhooyr.io/websocket) is the modern, context-aware, maintained choice. gorilla/websocket was archived for a while and is still very common in older code. Also see Centrifugo (Go) and server-sent events (SSE) for one-way streams, which need no library at all.