Chi Router: Context Values vs URL Params
In this tutorial, you'll learn about Chi Router: Context Values vs URL Params. We cover key concepts, practical examples, and best practices.
Chi router parameters -- Access URL parameters correctly in Chi router using chi.URLParam() helper instead of direct context lookups.
The Problem
Chi stores URL parameters in the request context using custom keys. Accessing them with r.Context().Value() fails because Chi uses unexported key types. Always use chi.URLParam(r, "key") to extract path variables safely.
Wrong
r := chi.NewRouter()
r.Get("/users/{id}", func(w http.ResponseWriter, r *http.Request) {
id := r.Context().Value("id") // nil!
})
Output:
$ curl http://localhost:8080/users/42
// id is nil, handler panics on type assertion
Right
r := chi.NewRouter()
r.Get("/users/{id}", func(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
w.Write([]byte("User: " + id))
})
Output:
$ curl http://localhost:8080/users/42
User: 42
Prevention
- Always use chi.URLParam(r, "key") for path parameters
- Use chi.URLParamFromCtx(ctx, "key") if you only have a context
- Use r.URL.Query().Get("key") for query string parameters
- Chi supports regex: r.Get("/users/{id:[0-9]+}", handler)
- Middleware can access params via chi.RouteContext(r.Context())
Common Mistakes with router chi
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging
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