路由组的作用
Gin框架中的路由组可以帮助开发者更有效地管理Web应用程序中的路由,从而提高Web应用程序的可维护性。
- 区分版本
- 区分模块
简单的路由组
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
// 简单的路由组: v1
v1 := router.Group("/v1")
{
v1.POST("/login", loginEndpoint)
v1.POST("/submit", submitEndpoint)
v1.POST("/read", readEndpoint)
}
// 简单的路由组: v2
v2 := router.Group("/v2")
{
v2.POST("/login", loginEndpoint)
v2.POST("/submit", submitEndpoint)
v2.POST("/read", readEndpoint)
}
router.Run(":8080")
}
路由封装
- main.go
package main
import (
all_router "test/router"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
all_router.Router(router) // all_router是总路由的package名称
router.Run(":8080")
}
2.router/router.go 总路由
package all_router
import (
"test/controller/test01"
"test/controller/test02"
"github.com/gin-gonic/gin"
)
func Router(router *gin.Engine) {
te01 := router.Group("test01")
te02 := router.Group("test02")
test01.Router(te01)
test02.Router(te02)
}
3.业务路由及业务方法
test01
controller/test01/router.go
package test01
import (
"github.com/gin-gonic/gin"
)
func Router(test01 *gin.RouterGroup) {
test01.GET("/", Hello)
}
controller/test01/hello.go
package test01
import (
"net/http"
"github.com/gin-gonic/gin"
)
func Hello(ctx *gin.Context) {
ctx.String(http.StatusOK, "这是test01路由组来的")
}
test02
controller/test02/router.go
package test02
import (
"github.com/gin-gonic/gin"
)
func Router(test01 *gin.RouterGroup) {
test01.GET("/", Hello)
}
controller/test02/hello.go
package test02
import (
"net/http"
"github.com/gin-gonic/gin"
)
func Hello(ctx *gin.Context) {
ctx.String(http.StatusOK, "这是test02路由组来的")
}
4.运行效果:
http://127.0.0.1:8080/test01/
http://127.0.0.1:8080/test02/
项目结构