4

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.

Berti92
  • 441
  • 1
  • 6
  • 12
  • 1
    Another approach you could take: only include a function in a specific API version if it is brand new or its behaviour changed from a previous version. –  Feb 21 '17 at 18:27

1 Answers1

11

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)
Zoyd
  • 3,449
  • 1
  • 18
  • 27
  • 2
    Thank you very much - that's a really nice solution! – Berti92 Feb 22 '17 at 10:34
  • Nice and clean solution. A different problem but is there a way to enhance this in a way to be able to overwrite some methods? If a,b,c are common to still add all of them in the group but overwirte c in v2. At the moment you would need to remove c from the common group and add it both to v1 and v2 manually. – Stefanos Chrs May 20 '21 at 04:56