go http 如何提取product_category[]这样的数组参数呢?

product_category[]这样的参数,php的会把它转化为数组,go的话,难道要我自己拼接起?

阅读 3.1k
3 个回答

不用,拼接,对于名字一样的form元素,Go会用[]string来存储的。

比如:

package main

import (
    "net/http"
)

type helloHandler struct{}

func (h *helloHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()
    if ids, existed := r.PostForm["id"]; existed {
        for _, id := range ids {
            w.Write([]byte(id + ","))
        }
    }
}

func main() {
    http.Handle("/", &helloHandler{})
    http.ListenAndServe(":12345", nil)
}

假设传入:

<input name="id" value="1" />
<input name="id" value="2" />
curl 'http://127.0.0.1:12345' -d 'id=1&id=2'

会输出结果:

1,2,

如果你要传数组,推荐使用json
使用反射解析也便于构造结构体。

<input name="id[]" value="1" />
<input name="id[]" value="2" />

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题