Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value of array key from query in golang

Tags:

arrays

url

go

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

like image 763
Jeremy John Avatar asked Mar 18 '17 04:03

Jeremy John


1 Answers

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"}
like image 91
Bayta Darell Avatar answered Sep 20 '22 06:09

Bayta Darell