gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:25:52 26 4
gpt4 key购买 nike

我有这个问题

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

最佳答案

一种方法是循环遍历可能的值并在你进行时附加到 slice :

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

关于arrays - 如何从golang中的查询中获取数组键的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42870319/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com