如何将多个组添加到gin路由中以实现API版本继承?

huangapple go评论83阅读模式
英文:

How to add multiple groups to gin routing for api version inheritance?

问题

我目前正在使用Go + Gin开发一个API。

API应该包括一个版本字符串,例如字符串v1

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

这没有问题,因为我可以使用Gin创建一个组

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

但是...如果我启动一个新的API版本"v2",并且函数UserGetUsername中的代码没有改变,我必须执行以下操作

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

有没有更好的解决方案 - 也许像这样:

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

谢谢你的建议。

英文:

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

得分: 11

我不认为Gin提供这个功能,但编写起来很容易。

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)
    }
}

然后,你可以这样使用:

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)
英文:

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)

huangapple
  • 本文由 发表于 2017年2月22日 00:56:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/42373423.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定