Skip to content

Go HTTP Handler Pattern: ServeMux vs Custom

DodaTech Updated 2026-06-24 1 min read

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!)
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

  1. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  2. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  3. Using head and tail instead 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

**Does Go 1.22+ change pattern matching?**

Yes. Go 1.22 added method matching (GET /path), wildcards (/api/{id}), and precedence rules. Upgrade if you need cleaner routing.

Why does /api match /api and /api/?

Without trailing slash, /api is exact. With trailing slash, /api/ is a prefix pattern. The mux redirects /api to /api/ if both exist.

How does longest match work?

The mux always picks the most specific (longest) matching pattern. /api/users/ is longer than /api/, so it wins for /api/users/list.


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