如何在 HTTP 请求中获取数组

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

How to get array in http request

问题

对于这个请求 GET http://localhost:8080/path?my_key%5B%5D=3&my_key%5B%5D=4&my_key%5B%5D=5,我无法从 my_key 中获取数据。我尝试了 req.URL.Query()["my_key"]。如果我将请求编码从 my_key%5B%5D=4&my_key%5B%5D=5 改为 my_key=4&my_key=5,我就可以获取到数据。

如何以 my_key[]=value 的形式获取请求的 URL?

英文:

For this request GET http://localhost:8080/path?my_key%5B%5D=3&my_key%5B%5D=4&my_key%5B%5D=5

I can't get the data from my_key. I tried req.URL.Query()["my_key"]. I can get it if I change the request encoding to from my_key%5B%5D=4&my_key%5B%5D=5 to my_key=4&my_key=5

How can I get request URL's in form of my_key[]=value

答案1

得分: 3

使用 net/url

  1. package main
  2. import (
  3. "fmt"
  4. "net/url"
  5. )
  6. func main() {
  7. utmp := "http://localhost:8080/path?my_key%5B%5D=3&my_key%5B%5D=4&my_key%5B%5D=5"
  8. u, err := url.Parse(utmp)
  9. if err != nil {
  10. panic(err)
  11. }
  12. fmt.Println(u.Query()["my_key[]"])
  13. }

你的键是 my_key[] 而不是 my_key

英文:

Use the net/url package

  1. package main
  2. import (
  3. "fmt"
  4. "net/url"
  5. )
  6. func main() {
  7. utmp := "http://localhost:8080/path?my_key%5B%5D=3&my_key%5B%5D=4&my_key%5B%5D=5"
  8. u, err := url.Parse(utmp)
  9. if err != nil {
  10. panic(err)
  11. }
  12. fmt.Println(u.Query()["my_key[]"])
  13. }

https://play.golang.org/p/t2O7KnUbZOA

Your key is "my_key[]" not "my_key"

huangapple
  • 本文由 发表于 2015年8月26日 10:44:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/32217169.html
匿名

发表评论

匿名网友

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

确定