Skip to content

fix(router): keep group auto-404 in sync with root RouteNotFound#3052

Open
Solaris-star wants to merge 1 commit into
labstack:masterfrom
Solaris-star:fix/2485-group-404-fallback
Open

fix(router): keep group auto-404 in sync with root RouteNotFound#3052
Solaris-star wants to merge 1 commit into
labstack:masterfrom
Solaris-star:fix/2485-group-404-fallback

Conversation

@Solaris-star

Copy link
Copy Markdown

Summary

When a group has middleware, Echo auto-registers RouteNotFound routes with a nil handler so the group middleware still runs on 404s. Those handlers are filled from DefaultRouter.notFoundHandler.

e.RouteNotFound("/*", h) only installed h on the root tree node. It did not update r.notFoundHandler, so later group auto-404 routes kept the default JSON {"message":"Not Found"} instead of the root catch-all.

Fix

On DefaultRouter.Add, if method is RouteNotFound and path is /* or "", also set r.notFoundHandler = route.Handler.

Test plan

  • TestGroup_RouteNotFoundFallsBackToRoot (issue repro: /foo, /v0/foo, /v1/foo)
  • TestGroup_RouteNotFound* / TestGroup_UseMultipleTimes
  • go test .

Fixes #2485

Group.Use auto-registers nil-handler RouteNotFound routes so group
middleware still runs on 404s. Those handlers were filled from
r.notFoundHandler at registration time, which stayed the default even
after e.RouteNotFound("/*", h). Groups with middleware therefore used
the stock 404 JSON body instead of the root catch-all (labstack#2485).

When a RouteNotFound is added for /* or "", update r.notFoundHandler so
later group auto-404 routes inherit the same handler.

Fixes labstack#2485

@aldas aldas left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do not think adding a route should have side-effects like that to Router.

you can achieve same (global 404 handler) when you create Router with your own NotFoundHandler

so this

	e := echo.New()
	e.RouteNotFound("/*", func(c *echo.Context) error {
		return c.NoContent(http.StatusNotFound)
	})

should be

	e := echo.NewWithConfig(echo.Config{
		Router: echo.NewRouter(echo.RouterConfig{
			NotFoundHandler: func(c *echo.Context) error {
				return c.NoContent(http.StatusNotFound)
			},
		}),
	})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

RouteNotFound handler does not falls back to root one

2 participants