echo icon indicating copy to clipboard operation
echo copied to clipboard

How to make Not Found detection take effect before middleware

Open OneSeven opened this issue 9 months ago • 3 comments

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.

OneSeven avatar Apr 02 '25 07:04 OneSeven

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

aldas avatar Apr 02 '25 16:04 aldas

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

OneSeven avatar Apr 03 '25 01:04 OneSeven

But even logger and cors middleware run before echo checks if routes exists, maybe you can use group routing

g := e.Group("/api", yourMiddleware)
g.GET("/hello", yourHandler)

Now a non existent route will bypass yourMiddleware

wathika-eng avatar Apr 30 '25 04:04 wathika-eng