3

Hi I am passing a query parameter to my gin server like this:

curl -X POST \
'http://localhost:4000/url?X=val1&Y=val2&x[]=1&x[]=2'

This is then sent to the my gin handler function

func handler (c *gin.Context) {
    fmt.Println(c.Query("X"))
    fmt.Println(c.Query("Y"))
    fmt.Println(c.QueryArray("x"))
}

While c.Query("x") and c.Query("Y") works, c.QueryArray("x") does not work!

I am not sure what am I missing over here. I have tried the same with GET request as well and it does not work.

Other experiments that did not work for me are here:

fmt.Println(c.Params.Get("x"))
fmt.Println(c.Params.Get("gene"))
fmt.Println(c.PostFormArray("x"))
5
  • 2
    Can you try this curl -X POST 'http://localhost:4000/url?X=val1&Y=val2&x=1&x=2'? Commented Jun 12, 2017 at 19:51
  • Are you sure this is POST request? You do not have post body. Commented Jun 12, 2017 at 19:53
  • @jeevatkm That just worked.. Thanks a lot! Commented Jun 12, 2017 at 19:56
  • you're welcome, added answer with details. Commented Jun 12, 2017 at 20:24
  • The same issue with solution in gin repo. Commented Jun 14, 2022 at 14:39

2 Answers 2

9

Drafted answer from my comment for SO users.

Repeat field name with values:

curl -X POST 'http://localhost:4000/url?X=val1&Y=val2&x=1&x=2'

or:

Separated by commas:

curl -X POST 'http://localhost:4000/url?X=val1&Y=val2&x=1,2'
Sign up to request clarification or add additional context in comments.

Comments

0

This maybe over-engineered, but it got things done for me:

// @Param property_type query []uint32 false "property_types"
func (svc *HttpService) acceptListofQuery(c *gin.Context) {
    var propertyTypes []uint32
    propertyTypes, done := svc.parsePropTypes(c)
    if done {
        return
    }
    // ..... rest of logic here
    c.JSON(200, "We good")
}

func (svc *HttpService) parsePropTypes(c *gin.Context) ([]uint32, bool) {
    var propertyTypes []uint32
    var propertyTypesAsString string
    var propertyTypesAsArrayOfStrings []string
    propertyTypesAsString, success := c.GetQuery("property_types")
    propertyTypesAsArrayOfStrings = strings.Split(propertyTypesAsString, ",")
    if success {
        for _, propertyTypeAsString := range propertyTypesAsArrayOfStrings {
            i, err := strconv.Atoi(propertyTypeAsString)
            if err != nil {
                svc.ErrorWithJson(c, 400, errors.New("invalid property_types array"))
                return nil, true
            }
            propertyTypes = append(propertyTypes, uint32(i))
        }
   }
    return propertyTypes, false
}

Then you can send something like:

curl -X POST 'http://localhost:4000/url?property_types=1,4,7,12

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.