英文:
Does golang request.ParseForm() work with "application/json" Content-Type
问题
使用Go语言(1.4)中的简单HTTP服务器,如果将content-type设置为"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
打印结果:map[foo:[bar]]
对于以下curl请求,处理程序不会打印表单值:
curl -H "Content-Type: application/json" -d '{"foo":"bar"}' http://localhost:3000
打印结果:map[]
英文:
Using a simple HTTP server in Go (1.4), the request form is empty if content-type is set to "application/json". Is this intended?
The simple http handler:
func (s Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
log.Println(r.Form)
}
For this curl request, the handler prints the correct form values:
curl -d '{"foo":"bar"}' http://localhost:3000
prints: map[foo:[bar]]
For this curl request, the handler does not print the form values:
curl -H "Content-Type: application/json" -d '{"foo":"bar"}' http://localhost:3000
prints: map[]
答案1
得分: 12
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 {
// 处理错误
}
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 {
// 处理错误
}
log.Printf("%#v", v) // 对于你的输入,记录 struct { Foo string "json:\"foo\"" }{Foo:"bar"}
}
英文:
ParseForm does not parse JSON request bodies. The output from the first example is unexpected.
Here's how to parse a JSON request body:
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)
}
You can define a type to match the structure of your JSON document and decode to that type:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论