如何在gin路由中添加多个组以实现api版本继承? [英] How to add multiple groups to gin routing for api version inheritance?
本文介绍了如何在gin路由中添加多个组以实现api版本继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前正在使用Go + Gin开发API.
I'm currently working on a API with Go + Gin.
API应该包含一个版本字符串,例如字符串v1
The API should include a version string, for example the string v1
http://127.0.0.1:3000/v1/user/get_username
那没问题,因为我可以用Gin创建一个小组
That is no problem, because I can create a group with Gin
v1 := router.Group("/v1")
v1.GET("/user/get_username", modules.UserGetUsername)
但是...如果我启动一个新的API版本"v2",并且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)
谢谢您的建议.
推荐答案
我不认为Gin提供了此功能,但看起来很容易编写.
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)
这篇关于如何在gin路由中添加多个组以实现api版本继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文