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

huangapple go评论67阅读模式
英文:

How to get value of array key from query in golang

问题

我有一个查询

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

我想要获取 status 键的所有值,如下所示

> 1, 2, 3

我尝试了以下代码

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

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

英文:

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

答案1

得分: 14

一种方法是循环遍历可能的值,并在遍历过程中将其追加到切片中:

r.ParseForm()  // 解析请求体和查询,并将结果存储在r.Form中
var a []string
for i := 0; ; i++ {
	key := fmt.Sprintf("status[%d]", i)
	values := r.Form[key] // 表单值是一个字符串切片
	if len(values) == 0 {
        // 没有更多的值
		break
	}
	a = append(a, values[i])
	i++
}

如果你对查询字符串有控制权,可以使用以下格式:

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

并使用以下代码获取status的值:

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

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

huangapple
  • 本文由 发表于 2017年3月18日 12:03:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/42870319.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定