繁体   English   中英

如何在golang中从查询中获取数组键的值

[英]How to get value of array key from query in golang

我有这个问题

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

我想得到状态键的所有值

1,2,3

我试过这样的事

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

但它仅在查询没有数组键时有效: site.com/?status=1&status=2&status=3&name=John

一种方法是循环遍历可能的值并随时附加到切片:

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++
}

如果您可以控制查询字符串,则使用以下格式:

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

并使用以下方式获取状态值

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM