Golang Gin-Gonic 将路由拆分成多个文件

Golang Gin-Gonic Split Routes into Multiple Files

我希望将我的 routes.go 拆分成多个文件,以便每个组都在自己的包中。有人能给我指出一些代码示例吗?有人用 Gin 做了这个?

package auth
...
auth = route.Group("/auth"){
    auth.GET(...
    auth.POST(...
}
...

package users
...
user = route.Group("/user"){
    user.GET(...
    user.POST(...
}
...

package main
import (
     "auth"
     "users"
)
...
router = gin.Default()
router.Register(auth.auth, users.user)
router.Run()
...

实现方法是在每个函数中创建一个函数,将路由作为参数,然后将路由添加到参数中:

package auth
import "...gin"
func Routes(route *gin.Engine)
auth := route.Group("/auth"){
    auth.GET(...
    auth.POST(...
}
...

package users
import "...gin"
func Routes(route *gin.Engine)
user := route.Group("/user"){
    user.GET(...
    user.POST(...
}
...

package main
import (
     "github.com/username/package/sub/auth"
     "github.com/username/package/sub/users"
     "github.com/gin-gonic/gin"
)
...
router := gin.Default()
auth.Routes(router) //Added all auth routes
user.Routes(router) //Added all user routes
router.Run()
...

再举个例子,视角不同...主组在主文件,子组在一个目录的不同文件中groups

package groups
import "...gin"
func Customer(g *gin.RouterGroup) {
  g.GET("/authorize", customer.Authorize)
  g.POST("/register", customer.Register)
}
...

package groups
import "...gin"
func Info(g *gin.RouterGroup) {
  g.GET("/car-color", controllers.CarColorsList)
  g.GET("/car-type", controllers.CarTypesList)
  g.GET("/car-manufacturer", controllers.CarManufacturersList)
  g.GET("/car-model", controllers.CarModelsList)
}
...

package main
import (
     "github.com/gin-gonic/gin"
     "github.com/username/package/api/groups"
)
...
router := gin.Default()
v1 := router.Group("/v1")
{
 v1.Use(AuthMiddleware)
 groups.Info(v1.Group("/info"))
 groups.Customer(v1.Group("/customer"))
}
router.Run()
...