Home > database >  Golang gin pass a default value
Golang gin pass a default value

Time:11-23

I have api and diffrenet routes like /v1.1/test and /v1/test for this two route I run different worker version which is v1.1 or v1, My question is how can I pass this version info to router

This is my main.go

   v1 := router.Group("/v1")
   {
       v1.GET("/test", getTest)
)
   }

   v1_1 := router.Group("/v1.1")
   {

       v1_1.GET("/test", getTest)
   }

In here I have getTest function

func getTest(c *gin.Context) {

    fmt.Println(<I want to print version>)
    task, err := zr.Push("test_v1", Test{Task: "exchanges"})
    getTestResponse(c, task, err)
}

And I have a possible solution which is using closure, may be can solve it, but I could not do it

CodePudding user response:

Warning : I don't use gin. But see below nonetheless.

A closure may do the trick. When you build a closure, always try to think about what type of function you need, and create a function that will return this type. In your case, you need a gin handler.

Here is an example where you can act differently based on the version :

func getTest(version string) func(c *gin.Context) {
    return func(c *gin.Context) {
        switch version {
        case "v1":
        // do what you need to do to handle old version
        default:
        // do something else by default
        }
    }
}

Or if you simply want to print like you do in your trivial example :

func getTest(version string) func(c *gin.Context) {
    return func(c *gin.Context) {
        fmt.Println(version)
        task, err := zr.Push("test_"   version, Test{Task: "exchanges"})
        getTestResponse(c, task, err)
    }
}

Now, you can wrap that in your router :

v1 := router.Group("/v1")
{
    v1.GET("/test", getTest("v1"))
}

v1_1 := router.Group("/v1.1")
{
    v1_1.GET("/test", getTest("v1.1"))
}
  •  Tags:  
  • go
  • Related