go-chi / go-chi/chi

URL params are not available inside middleware on the root router

Open
#892 7 comments 0 reactions 0 assignees View on GitHub
Dominant language
Go
Stars
22.8k
Forks
1.2k
Avg merge
5h 17m
Merged PRs (30d)
10

Description

When I create a middleware to log the `id` URL parameter, which exists in the route I request, the value is always empty. I do get a value inside the handler itself

```Go
r := chi.NewRouter()

r.Use(func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
log.Println(id)
h.ServeHTTP(w, r)
})
})

r.Get("/test/{id}", func(w http.ResponseWriter, r *http.Request) {
id := router.Param(r, "id").String()
io.WriteString(w, id)
})
```

When I move this code to a `Group`, the URL param will become available inside the middleware.

```Go
r := chi.NewRouter()

r.Group(func(r chi.Router) {
r.Use(func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
log.Println(id)
h.ServeHTTP(w, r)
})
})

r.Get("/test/{id}", func(w http.ResponseWriter, r *http.Request) {
id := router.Param(r, "id").String()
io.WriteString(w, id)
})
})
```

I think this behavior is quite strange and prone to errors

Tested with the latest version (5.0.11)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.