0

I am using gin to implement the original PHP API. Currently, there are online requests similar to

/path?a[]=1&a[]=2&b[0]=1&b[1]=2&c[0][age]=1&c[0][name]=abc.

How can I get such array parameters in gin?

get value like:

a=["1", "2"]
b=["1", "2"]
c=[{"age": "1", "name": "abc"}]

It seems that gin does not support this parameter. Is there any elegant way to get such parameters?

1
  • Does my answer help? Commented Nov 22, 2020 at 5:07

1 Answer 1

2

Refer this Pull Request on github,I found a possible solution to get the parameters like a[]=1&a[]=2:

enter image description here

Code in golang:

// Return an array
a, _ := ctx.GetQueryArray("a[]") // Or just use QueryArray("a[]") directly.
ctx.JSON(200, gin.H{
    "a[]": a,
})

Parameters like &b[0]=1&b[1]=2, You could use QueryMap directly(This wouldn't return an array,though):

enter image description here

// Return a map.
ctx.JSON(200, gin.H{
    "b": ctx.QueryMap("b"),
})

I don't think there is a direct way to get an array with map.I did some changes from the source code of get in gin.Context(hardcode):

var dicts []map[string]string
key := "a"
queryMap := ctx.Request.URL.Query()
//log.Println(dicts) // dicts[0] except
for k, v := range queryMap {
    if i:= strings.IndexByte(k, '['); i >= 1 && k[0:i] == key{
        if j := strings.IndexByte(k[i+1:], ']'); j >= 1{
            index, _ := strconv.Atoi(k[i+1: i+j+1]) // get the index of slice
            if index > len(dicts){
                ctx.JSON(200, gin.H{
                    "403": "Check your data",
                })
                return
            }
            if index == len(dicts){
                tmp := make(map[string]string)
                dicts = append(dicts, tmp)
            }
            pre :=strings.IndexByte(k[i+j+2:], '[')
            last:=strings.IndexByte(k[i+j+2:], ']')
            dicts[index][k[i+j+3+pre: i+j+2+last]] = v[0]
        }
    }
}
ctx.JSON(200, gin.H{
    "a": dicts,
})

Example: enter image description here When data out of bounds: enter image description here

Sign up to request clarification or add additional context in comments.

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.