dongyunwei8596 2017-02-21 16:56 采纳率: 100%
浏览 404
已采纳

如何在gin路由中添加多个组以实现api版本继承?

I'm currently working on a API with Go + Gin.

The API should include a version string, for example the string v1

http://127.0.0.1:3000/v1/user/get_username

That is no problem, because I can create a group with Gin

v1 := router.Group("/v1")
v1.GET("/user/get_username", modules.UserGetUsername)

But... if I start a new API-Version "v2" and the code within the function UserGetUsername didn't changed I must do the following

v1 := router.Group("/v1")
v1.GET("/user/get_username", modules.UserGetUsername)
v2 := router.Group("/v2")
v2.GET("/user/get_username", modules.UserGetUsername)

Is there a nicer solution for that - maybe something like that:

v1_v2 := router.Group("/v1").AnotherGroup("/v2")
v1_v2.GET("/user/get_username", modules.UserGetUsername)

Thank you for your suggestions.

  • 写回答

1条回答 默认 最新

  • douyueju2912 2017-02-21 21:48
    关注

    I don’t think Gin provides this, but it looks easy to write.

    type GroupGroup struct {
        groups []*gin.RouterGroup
    }
    
    func NewGroupGroup(groups []*gin.RouterGroup) GroupGroup {
        return GroupGroup {
            groups,
        }
    }
    
    func (g *GroupGroup) handle(method string, path string, handler gin.HandlerFunc) {
        for _, group := range g.groups {
            group.Handle(method, path, handler)
        }
    }
    

    Then, you can use it like so :

    v1 := router.Group("/v1")
    v2 := router.Group("/v2")
    
    g := NewGroupGroup([]*gin.RouterGroup { v1, v2 })
    
    g.handle(http.MethodGet, "hello", sayHello)
    g.handle(http.MethodPost, "goodbye", sayGoodbye)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制