代码地址
- 实现原理: 利用go的切片类型和包的init方法,在引入包的使用调用包的init方法,在init方法中,将本模块的路由,append到全局变量中,然后在main中遍历存放路由的变量,进行路由注册
// main.go
package main
import (
_ "mirco_learn/app"
"mirco_learn/routes"
)
// import引入的时候,线引入app包,就加载app.go app.go中import了api,会调用api/route.go的init方法,然后就会把good的路由注册进来
func main() {
//初始化路由
gin := routes.InitRoutes()
gin.Run()
}
mirco_learn/routes/routes.go 实现路由注册和路由的初始化
package routes
import (
"mirco_learn/middleware"
"github.com/gin-gonic/gin"
)
type Router func(*gin.Engine)
// 使用一个全局变量, 其他部分在注册路由前,使用Register方法,把路由注册进来,然后再调用initRoute 进行路由加载
var routers = []Router{}
func InitRoutes() *gin.Engine {
r := gin.Default()
middleware.InitMiddleware(r)
for _, route := range routers {
route(r)
}
return r
}
// 注册route 其余模块在init中调用RegisterRoute注册
func RegisterRoute(routes ...Router) {
routers = append(routers, routes...)
}
mirco_learn/app/app.go
package app
import (
_ "mirco_learn/app/api"
)
mirco_learn/app/api/route.go
package api
import (
apiV1 "mirco_learn/app/api/v1"
"mirco_learn/routes"
"github.com/gin-gonic/gin"
)
func init() {
routes.RegisterRoute(Routes)
}
func Routes(g *gin.Engine) {
//g.GET("getgoods",GetGoods)
goods := g.Group("goods")
{
goods.GET("/", apiV1.GetGoods)
}
}