Skip to content

How to make Not Found detection take effect before middleware #2761

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
OneSeven opened this issue Apr 2, 2025 · 2 comments
Open

How to make Not Found detection take effect before middleware #2761

OneSeven opened this issue Apr 2, 2025 · 2 comments

Comments

@OneSeven
Copy link

OneSeven commented Apr 2, 2025

e := echo.New()
e.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
	return func(c echo.Context) error {
		log.Println("middleware...")
		return next(c)
	}
})
e.GET("/hello", func(c echo.Context) error {
	return c.String(http.StatusOK, "Hello, World!")
})
e.Logger.Fatal(e.Start(":1323"))

http://127.0.0.1:1323/test

Accessing a non-existent route, but passing through the middleware first, this situation also applies to route groups

There is usually an authorization authentication in the middleware. If you access a non-existent route, it will go through the middleware first, which will waste unnecessary processing and add additional judgment logic.

@aldas
Copy link
Contributor

aldas commented Apr 2, 2025

c.Path() will return empty string if there is no route match. NB: if e.RouteNotFound() exists and is matched - it will have path.

@OneSeven
Copy link
Author

OneSeven commented Apr 3, 2025

c.Path() will return empty string if there is no route match. NB: if e.RouteNotFound() exists and is matched - it will have path.

e.RouteNotFound() also takes effect after the middleware, and needs to be manually processed in the middleware

e := echo.New()
e.RouteNotFound("/*", func(c echo.Context) error {
	log.Println("404 not found")
	return c.NoContent(http.StatusNotFound)
})
e.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
	return func(c echo.Context) error {
		// In the route group, /group/* will be returned, and you still need to manually match the routing table.
		// This method is not applicable
		if c.Path() == "" {
			return echo.NewHTTPError(http.StatusNotFound, "Not Found")
		}
		log.Println(c.Path(), "middleware...")
		return next(c)
	}
})
e.GET("/hello", func(c echo.Context) error {
	return c.String(http.StatusOK, "Hello, World!")
})
e.Logger.Fatal(e.Start(":1323"))

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

No branches or pull requests

2 participants