Gin框架系列教程(4)- Router 路由封装
今天我们研究一下gin中的路由应该怎么配置:
首先我们先测试一个简单的路由,也就是默认路由:
package main
import (
"github.com/gin-gonic/gin"
)
func main(c *gin.Context) {
r := gin.Default()
r.GET("/", func(c *gin.Context) {
c.String(200, "hello world")
})
r.run('9000')
这个就是首页路由,很简短。
那么gin框架中怎么封装路由呢,就是把多个路由按照一定规则进行拆分封装。下面代码展示:
一、主入口文件初始化路由
r := gin.Default()
// 路由初始化
routers.Routers(r)
二、新建routers文件夹,以及user,member路由文件夹,路由分组,三个示例文件(routers.go,member.go,user.go)
routers.go
//router.go
package routers
import (
"gin_alingfeng/routes/memberRouter"
"gin_alingfeng/routes/userRouter"
"github.com/gin-gonic/gin"
)
func Routers(r *gin.Engine) {
//api分组路由
api := r.Group("/api")
memberRouter.MemberApiRouter(api)
userRouter.UserApiRouter(api)
//直接路由
memberRouter.MemberRouter(r)
userRouter.UserRouter(r)
}
member.go
package memberRouter
import (
"gin_alingfeng/controllers/userController"
"gin_alingfeng/middleware"
"github.com/gin-gonic/gin"
)
func MemberApiRouter(api *gin.RouterGroup) {
api.GET("/member", func(c *gin.Context) {
c.String(200, "hello world member")
})
}
func MemberRouter(r *gin.Engine) {
r.GET("/member2", middleware.Cors(), middleware.Logs, userController.User)
}
user.go
package memberRouter
import (
"gin_alingfeng/controllers/userController"
"gin_alingfeng/middleware"
"github.com/gin-gonic/gin"
)
func MemberApiRouter(api *gin.RouterGroup) {
api.GET("/member", func(c *gin.Context) {
c.String(200, "hello world member")
})
}
func MemberRouter(r *gin.Engine) {
r.GET("/member2", middleware.Cors(), middleware.Logs, userController.User)
}
结构如下:
还没有评论,快来发表第一个评论吧