Closed 4strodev closed 2 years ago
Echo has way of creating collection of routes (called Group
) that share same path prefix and have same middlewares.
Note:
sg := g.Group("/subgroup")
g.GET
that route is immediately registered on Echo router. func main() {
e := echo.New()
// signature for creating Group is `Group(prefix string, middleware ...MiddlewareFunc)` so
// you can add any number of middlewares to the group
g := e.Group("/users", middleware.CORS(), middleware.RequestID())
g.GET("/:id", func(c echo.Context) error {
return c.JSON(http.StatusOK, map[string]string{"username": "test"})
})
if err := e.Start(":8080"); err != http.ErrServerClosed {
log.Fatal(err)
}
}
A little bit more evolved example
package main
func main() {
e := echo.New()
api := e.Group("/api", middleware.Logger(), middleware.Recover())
users.registerUserRoutes(api)
if err := e.Start(":8080"); err != http.ErrServerClosed {
log.Fatal(err)
}
}
package users
// this function you can add under `users` package for example to split your application logic
// into separate domain packages
func registerUserRoutes(parent *echo.Group) {
// signature for creating Group is `Group(prefix string, middleware ...MiddlewareFunc)` so
// you can add any number of middlewares to the group
g := parent.Group("/users", middleware.CORS(), middleware.RequestID())
g.GET("/:id", func(c echo.Context) error {
return c.JSON(http.StatusOK, map[string]string{"username": "test"})
})
}
Issue Description
I used to work with fiber. And a feature that I love is that you can mount a router under a path. This allows you to create a router separate from app instance and then mount that under your application. Even you can create a group and then under this group mount the routers that you need for example.
main.go
This allows me to create a group for API routes and in this group mount the routers of this API.
Is there a way to do something similar with echo?