42

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
        }
    }
}
Zoyd
  • 3,449
  • 1
  • 18
  • 27
codec
  • 7,978
  • 26
  • 71
  • 127

4 Answers4

72

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

Chris Cherry
  • 28,118
  • 6
  • 68
  • 71
  • 3
    why choose map[string][]string instead of map[string]string? – R wang Jun 07 '19 at 02:06
  • 15
    In a query string, a param name can be used more than once, using []string for the value of the map allows them to capture all of different values that share the same param name. https://play.golang.org/p/FtQIz_ePF_N – Chris Cherry Jun 07 '19 at 22:10
26

you can get query parameters using :

c.Query("key") -> returns string
or
c.GetQuery("key") -> returns (string, bool->ok)
Amirreza Saki
  • 601
  • 7
  • 8
17

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

ellimist
  • 586
  • 3
  • 12
0

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.

Ryan Loggerythm
  • 2,877
  • 3
  • 31
  • 39