How to make Not Found detection take effect before middleware
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.
c.Path() will return empty string if there is no route match. NB: if e.RouteNotFound() exists and is matched - it will have path.
c.Path()will return empty string if there is no route match. NB: ife.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"))
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