Go Academy · Lesson

Connection Management

Handle disconnects.

Lesson 4 of 413 steps

Connection Management is a free Go Academy lesson on CoddyKit. This is lesson 4 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, and your progress syncs across the web and the CoddyKit app. The Go Academy course includes 4 lessons in total.

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
Free to start

Learn Go with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

Is the “Connection Management” lesson free?

Yes — any 3 lessons of the Go Academy learning path, including “Connection Management”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Go Academy course includes 4 lessons in total.

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, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.

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

  1. WebSocket Basics
  2. Using gorilla/websocket
  3. Broadcasting Messages
  4. Connection Management
← Back to Go Academy