Skip to content

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

@ezraisw

Description

@ezraisw

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

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions