13

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

2
  • can you put status value to like this one instead? like site.com?&status=1,2,3? Commented Mar 18, 2017 at 4:10
  • I can't because my frontend is using a react js package component which convert the selection query to be ?status[0]=1&status[1]=2&status[1]=3 Commented Mar 18, 2017 at 4:12

1 Answer 1

17

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[0])
    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"}
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.