简体   繁体   中英

Golang gin pass a default value

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

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

gin can process parameters in path through Context like this:

package main

import (
    "github.com/gin-gonic/gin"
    "net/http"
)

func main() {
    router := gin.Default()

    router.GET("/:version/test", getTest)

    router.Run(":8080")
}

func getTest(c *gin.Context) {
    version := c.Param("version")
    c.String(http.StatusOK, "version: %s\n", version)
}

output

$ curl 'http://localhost:8080/v1/test'  
version: v1
$ curl 'http://localhost:8080/v1.1/test'
version: v1.1

you can find more details here: https://github.com/gin-gonic/gin#querystring-parameters

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM