How to get all query parameters from go *gin.context object

111.7k views Asked by At

I am looking at https://godoc.org/github.com/gin-gonic/gin documentation for a method which returns list of all the query parameters passed. There are methods which return value of a query parameter. Is there any method which returns list of all the query parameters passed ? It's ok if we don't get values. I am fetching the values of the query parameter using the following code. But this code can only check if the query parameter exists or not.

func myHandler(c *gin.Context) {

    // check for query params
    if queryParam, ok := c.GetQuery("startingIndex"); ok {
        if queryParam == "" {
            c.Header("Content-Type", "application/json")
            c.JSON(http.StatusNotFound,
                gin.H{"Error: ": "Invalid startingIndex on search filter!"})
            c.Abort()
            return
        }
    }
}
6

There are 6 answers

2
Chris Cherry On BEST ANSWER

You should be able to do c.Request.URL.Query() which will return a Values which is a map[string][]string

0
ellimist On

If you're talking about GET query params, you can retrieve them using:

c.Request.URL.Query()

You'll get back a Values type which is a map[string][]string

Docs: https://golang.org/pkg/net/url/#URL.Query

0
Petru Bantis On

If you know what type is come you can use

ctx.GetString("string")
ctx.GetBool("bool")
ctx.GetInt("int")
0
Amirreza Saki On

you can get query parameters using :

c.Query("key") -> returns string
or
c.GetQuery("key") -> returns (string, bool->ok)
0
Ryan Loggerythm On

Carrying on from @ctcherry's answer...

func myAPIEndpoint(c *gin.Context) {

    paramPairs := c.Request.URL.Query()
    for key, values := range paramPairs {
        fmt.Printf("key = %v, value(s) = %v\n", key, values)
    }
}

Keep in mind that a given key may contain multiple values, so your values is an array.

2
Sam On

If you want to get the value from the last part of the URL "api/abc/value". Use the .Param method that collects from the url. Don't forget to change your URL to: "api/abc/:value" (the 2 dots are very important)

code example:


func ReturnPersonalitie(c *gin.Context) {
    vars := c.Param("id")
    id, err := strconv.Atoi(vars)
    if err != nil {
        fmt.Println("error: ", err)
    }

    for _, personalitie := range models.Personalities {
        if personalitie.Id == id {
            c.JSON(http.StatusOK, personalitie)
        }
    }
    fmt.Printf("Value id: %d", id)
}

calling:


r.GET("/api/personalidades/:id", func(ctx *gin.Context) {
    controllers.ReturnPersonalitie(ctx)
})

For more information read: https://gin-gonic.com/docs/examples/param-in-path/