golang的request.ParseForm()方法能够处理”application/json”的Content-Type吗?

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

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
 }

huangapple
  • 本文由 发表于 2014年12月22日 09:17:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/27595480.html
匿名

发表评论

匿名网友

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

确定