在 Go (1.4) 中使用简单的 HTTP 服务器,如果内容类型设置为“application/json”,则请求表单为空。这是故意的吗?
简单的 http 处理程序:
func (s Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
log.Println(r.Form)
}
对于这个 curl 请求,处理程序打印正确的表单值:
curl -d '{"foo":"bar"}' http://localhost:3000
prints: map[foo:[bar]]
对于这个 curl 请求,处理程序不打印表单值:
curl -H "Content-Type: application/json" -d '{"foo":"bar"}' http://localhost:3000
prints: map[]
最佳答案
ParseForm 不解析 JSON 请求主体。第一个示例的输出是 unexpected .
解析 JSON 请求正文的方法如下:
func (s Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var v interface{}
err := json.NewDecoder(r.Body).Decode(&v)
if err != nil {
// handle error
}
log.Println(v)
}
您可以定义一个类型来匹配您的 JSON 文档的结构并解码为该类型:
func (s Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var v struct {
Foo string `json:"foo"`
}
err := json.NewDecoder(r.Body).Decode(&v)
if err != nil {
// handle error
}
log.Printf("%#v", v) // logs struct { Foo string "json:\"foo\"" }{Foo:"bar"} for your input
}
关于go - golang request.ParseForm() 是否与 "application/json"Content-Type 一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27595480/