How do you decode query strings containing arrays in Go?

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

How do you decode query strings containing arrays in Go?

问题

你可以使用Go语言来解码这样结构化的查询字符串。目前的代码如下:

query := r.URL.Query()
for k, _ := range query {
    fmt.Printf("%s\n", k)
}
ids := query.Get("ids[]")
if ids != "" {
    fmt.Printf("Ids: %s\n", ids)
}

目前的结果是:

ids[]
Ids: 1

是否有内置的方法来支持这个格式的查询字符串,还是我需要手动解析它?

英文:

How do you use Go to decode a query string structured like this?

/comments?ids[]=1&ids[]=2&ids[]=3

Right now this code:

query := r.URL.Query()
for k, _ := range query { fmt.Printf("%s\n", k) }
ids := query.Get("ids[]")
if (ids != "") {
    fmt.Printf("Ids: %s\n", ids)
}

results in:

ids[]
Ids: 1

Is there a built-in way to support this or am I going to have to parse this out by hand?

答案1

得分: 5

看起来你可以通过调用以下代码来实现:

r.ParseForm()
fmt.Printf("表单中的Ids: %s\n", r.Form["ids[]"])

这将产生以下结果:

表单中的Ids: [1 2 3]
英文:

It looks like you can do this by calling

r.ParseForm()
fmt.Printf("Ids from form: %s\n", r.Form["ids[]"])

which yields the following results:

Ids from form: [1 2 3]

huangapple
  • 本文由 发表于 2013年12月2日 12:16:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/20320739.html
匿名

发表评论

匿名网友

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

确定