Httprouter: Panic on Missing Path Variable
In this tutorial, you'll learn about Httprouter: Panic on Missing Path Variable. We cover key concepts, practical examples, and best practices.
Httprouter parameters -- Access httprouter path variables safely by checking the Params slice length before indexing.
The Problem
httprouter stores path variables as a slice of Param structs. Unlike mux or Chi, it does not provide a safe typed getter. Direct indexing like ps[0] panics when no params are present.
Wrong
router := httprouter.New()
router.GET("/users/:id", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
id := ps[0].Value // Panics if no params!
})
Output:
$ curl http://localhost:8080/users
// panic: runtime error: index out of range
Right
router.GET("/users/:id", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
id := ps.ByName("id")
if id == "" {
http.Error(w, "missing id", 400)
return
}
w.Write([]byte("User: " + id))
})
Output:
$ curl http://localhost:8080/users/42
User: 42
$ curl http://localhost:8080/users
missing id (400 status)
Prevention
- Use ps.ByName("name") for safe param access
- Never index ps directly unless you checked len(ps) > 0
- httprouter uses colon for params: /users/:id not {id}
- Catch-all params use *name: /files/*filepath
- httprouter is not http.Handler compatible without wrapping
Common Mistakes with router httprouter
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
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