Based on @Andy 's idea, I come up with a solution, that supports detachable nested routes.
The current folder structure is as follows:
.
├── routes
│ ├── index.go
│ └── music.go
└── server.go
...where server.go
is the project main entry, belongs to the main
package, while index.go
and music.go
belong to routes
package.
The endpoints are
"/api" -> index.go
"/api/music" -> music.go
First in index.go
we define a function for using routes at this level.
func UseRoute(group *echo.Group, routes func(group *echo.Group)) {
routes(group)
}
Then,
in server.go
func main() {
e := echo.New()
apiGroup := e.Group("/api")
routes.ActivateIndex(mainGroup)
}
in index.go
var mainGroup *echo.Group
func ActivateIndex(g *echo.Group) {
mainGroup = g
UseRoute(mainGroup, IndexRoutes)
// sub routes
musicGroup := mainGroup.Group("/music")
ActivateMusic(musicGroup)
}
and in music.go
var musicGroup *echo.Group
func ActivateMusic(g *echo.Group) {
musicGroup = g
UseRoute(musicGroup, MusicRoutes)
}
Note: IndexRoutes
, MusicRoutes
etc. are functions that specify endpoints at this level.
e.g.
func IndexRoutes(group *echo.Group) {
group.GET("/", sayHello)
group.GET("/user/:id", getDetail)
group.POST("/user", addUser)
}
In this way, the routes can be defined in different .go
files, making the business logic clearer.
For example, to extend the nested level, we can create another ActivateHiphop
function in hiphop.go
, also import the new sub-routes at ActivateMusic
function from music.go
, so that "/api/music/hiphop"
can be pointed to hiphop.go
.
p.s. To add more routes in /api
level, just create more endpoints in IndexRoutes
function.