Go HTTP Handler Pattern: ServeMux vs Custom
Go HTTP handler patterns -- Learn how Go's default ServeMux routing works and avoid common pattern matching pitfalls that lead to 404 errors and route conflicts.
The Problem
The default http.ServeMux uses prefix matching, not exact matching. A pattern like /api/ matches any path starting with /api/, while /api without trailing slash matches exactly /api only. This subtle difference causes unintended route collisions and 404 errors.
Wrong
http.HandleFunc("/api/", apiHandler)
http.HandleFunc("/api/users", usersHandler)
Output:
$ curl http://localhost:8080/api/users
// apiHandler handles it (wrong!)
Right
http.HandleFunc("/api/", apiHandler)
http.HandleFunc("/api/users/", usersHandler)
Output:
$ curl http://localhost:8080/api/users
usersHandler handles it (correct!)
Prevention
- Use trailing slash for prefix patterns: /api/ matches /api/...
- Use exact patterns (no trailing slash) for single routes like /api
- Go 1.22+ supports method-based patterns: GET /api/users
- Longest match wins: /api/users/ beats /api/ for paths under /api/users/
- Test route matching with a table-driven test before deploying
Common Mistakes with http handler pattern
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
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