Connection Management
Handle disconnects.
Connection Management is a free Go Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Connections Do Not Last Forever
Clients close tabs, lose Wi-Fi, or crash. Robust WebSocket servers must detect disconnects, clean up resources, and free goroutines. Otherwise you leak memory and sockets.
The Close Handshake
A clean shutdown sends a close frame in both directions. gorilla surfaces this as an error from ReadMessage with a close code you can inspect.
if websocket.IsCloseError(err, websocket.CloseNormalClosure) {
// graceful close
}Ping/Pong Keepalive
To detect a half-open connection (peer vanished without closing), the server periodically sends ping control frames and expects pong replies.
conn.SetPongHandler(func(string) error {
conn.SetReadDeadline(time.Now().Add(60 * time.Second))
return nil
})Read Deadlines
Set a read deadline so a dead peer eventually errors out instead of blocking forever. Refresh it whenever a pong arrives.
conn.SetReadDeadline(time.Now().Add(60 * time.Second))The Ping Ticker
A ticker in the writer goroutine fires periodic pings. If a write fails, the connection is dead and you exit.
ticker := time.NewTicker(54 * time.Second)
defer ticker.Stop()
for range ticker.C {
if err := conn.WriteMessage(websocket.PingMessage, nil); err != nil {
return
}
}Cleanup on Exit
When a read or write loop ends, unregister the client and close the connection. defer makes this reliable even on panic.
defer func() {
hub.unregister <- client
conn.Close()
}()Two Goroutines per Connection
The standard pattern runs a readPump and a writePump per connection. When one detects an error, it triggers cleanup that stops the other (often by closing the send channel).
Write Deadlines Too
Set write deadlines so a stuck write does not hang a goroutine forever. A timed-out write returns an error and you tear down the connection.
conn.SetWriteDeadline(time.Now().Add(10 * time.Second))Graceful Server Shutdown
On server shutdown, send each client a close frame and wait briefly. Combine with http.Server.Shutdown and a context deadline.
conn.WriteMessage(websocket.CloseMessage,
websocket.FormatCloseMessage(websocket.CloseGoingAway, "bye"))Reconnect on the Client
Disconnects are normal. Clients should implement exponential backoff reconnect logic. The server side just needs to handle each connect/disconnect cleanly.
Runnable: Timeout Detection Analogy
WebSocket keepalive needs the library; this standard-library program models a deadline-based liveness check with a timer and a channel.
package main
import (
"fmt"
"time"
)
func main() {
pong := make(chan struct{})
go func() {
time.Sleep(20 * time.Millisecond) // simulate a slow/absent peer
_ = pong // no pong sent -> dead connection
}()
select {
case <-pong:
fmt.Println("alive")
case <-time.After(10 * time.Millisecond):
fmt.Println("no pong: closing dead connection")
}
}Quick Check
Test your understanding of connection management.
Recap
You learned connection management:
- Handle the close handshake and inspect close codes
- Use ping/pong plus read/write deadlines to detect dead peers
- Run read and write pumps; clean up with
defer - Shut down gracefully with close frames; clients reconnect with backoff
Frequently asked questions
Is the “Connection Management” lesson free?
Yes — the full text of “Connection Management” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.
What will I learn in “Connection Management”?
Handle disconnects. You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Go Academy?
No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Connection Management” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Go Academy lesson?
Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- WebSocket Basics
- Using gorilla/websocket
- Broadcasting Messages
- Connection Management