11

我希望将我的 routes.go 拆分为多个文件,以便每个组都在自己的包中。有人可以指出一些有人用 Gin 完成此操作的代码示例吗?

IE

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()
...
4

2 回答 2

29

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

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()
...
于 2017-03-23T05:34:49.117 回答
3

另一个例子,不同的视角......主文件中的主组,放在一个目录中不同文件中的子组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()
...
于 2021-10-18T22:07:42.840 回答