Go Ws Close Handler
In this tutorial, you'll learn about WebSocket: Close Handling. We cover key concepts, practical examples, and best practices.
WebSocket close handling -- Handle close frames, unexpected disconnections, and cleanup resources properly.
The Problem
Without close handlers, disconnections are silent. Use SetCloseHandler and detect read errors for clean resource cleanup.
Wrong
conn, _ := upgrader.Upgrade(w, r, nil)
for {
_, msg, err := conn.ReadMessage()
if err != nil {
break // Disconnect detected but no cleanup
}
process(msg)
}
Output:
// Client disconnects silently. No cleanup of user session.
Right
conn.SetCloseHandler(func(code int, text string) error {
log.Printf("client disconnected: code=%d text=%s", code, text)
cleanupUserSession(conn)
message := websocket.FormatCloseMessage(code, "")
conn.WriteControl(websocket.CloseMessage, message, time.Now().Add(time.Second))
return nil
})
conn.SetPongHandler(func(string) error {
conn.SetReadDeadline(time.Now().Add(60 * time.Second))
return nil
})
for {
_, msg, err := conn.ReadMessage()
if err != nil {
if websocket.IsCloseError(err, websocket.CloseNormalClosure) {
log.Println("normal closure")
} else if websocket.IsUnexpectedCloseError(err) {
log.Println("unexpected close:", err)
}
break
}
process(msg)
}
Output:
// Clean disconnection handling. Resources released.
Prevention
- SetCloseHandler to handle close frames
- SetPongHandler with ReadDeadline for keepalive
- Use IsCloseError to check close codes
- Use IsUnexpectedCloseError for unexpected disconnects
- Always cleanup session/resources on disconnect
Common Mistakes with ws close handler
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro