Skip to content

Httprouter: Panic on Missing Path Variable

DodaTech Updated 2026-06-24 2 min read

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

  1. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  2. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  3. 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

**What is the difference between :param and *param?**

:param matches a single path segment. *param matches everything including slashes (catch-all).

Does httprouter redirect trailing slashes?

Yes, automatically. /users/ redirects to /users if only the latter is registered.

Can I use httprouter with standard middleware?

Yes. Use router.Handler(method, path, handler) which accepts http.Handler.


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