go-chi / go-chi/chi

Sub-routers returning 404 when using `middleware.SupressNotFound` on parent router

Open
#939 0 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

# Description
It seems that sub-routers are not properly matched after I applied `middleware.SupressNotFound`.
I investigated this and apparently `rctx.RoutePath` is modified without being restored in `middleware.SupressNotFound`.
This should be reproducible from the snippet I posted below.

# Action
## Expected Behavior
- Go to `http://localhost:8889/example/sub/hello`
- I should get "Hello World".
- Console should print "Route path /sub/hello"

## Actual
- Go to `http://localhost:8889/example/sub/hello`
- Instead I got "404 page not found" with 404 status. This is returned by the sub router, not the middleware.
- Console printed "Route path /hello"

*Actual result can be obtained by removing `middleware.SupressNotFound`.*

## Code
```go
package main

import (
"fmt"
"net/http"

"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)

func main() {
mr := chi.NewRouter()

mr.Route("/example", func(r chi.Router) {
r.Use(middleware.SupressNotFound(mr))
r.Use(func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rctx := chi.RouteContext(r.Context())
fmt.Println("Route path", rctx.RoutePath)
h.ServeHTTP(w, r)
})
})

r.Get("/other-hello", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("The Other Hello World"))
})

r.Route("/sub", func(r chi.Router) {
r.Get("/hello", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello World"))
})
})

})

http.ListenAndServe("0.0.0.0:8889", mr)
}
```

Contributor guide

Open the contributing guide

Research direction

Start at middleware.SupressNotFound and reproduce the nested /example/sub/hello route from the issue, observing chi.RouteContext(r.Context()).RoutePath before and after the middleware. Done means the sub-router returns "Hello World" and the route-path log remains "/sub/hello" when the middleware is applied.

Written by the indexing model from the issue text.

Assessment

Tech stack
go
Domain
api, backend
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.