简体   繁体   中英

How to get value of array key from query in golang

I have this query

site.com/?status[0]=1&status[1]=2&status[1]=3&name=John

I want to get all the values of status key like

1, 2, 3

I tried something like this

for _, status:= range r.URL.Query()["status"] {
    fmt.Println(status)
}

but it only works if the query is without array key: site.com/?status=1&status=2&status=3&name=John

One approach is to loop over the possible values and append to a slice as you go:

r.ParseForm()  // parses request body and query and stores result in r.Form
var a []string
for i := 0; ; i++ {
    key := fmt.Sprintf("status[%d]", i)
    values := r.Form[key] // form values are a []string
    if len(values) == 0 {
        // no more values
        break
    }
    a = append(a, values[i])
    i++
}

If you have control over the query string, then use this format:

 site.com/?status=1&status=2&status=3&name=John

and get status values using:

 r.ParseForm()
 a := r.Form["status"]  // a is []string{"1", "2", "3"}

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