go - golang request.ParseForm() 是否与 "application/json"Content-Type 一起工作

标签 go

在 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/

相关文章:

object - 类型断言非简约

go - Go 函数中返回变量的个数可变

Go: time.Format: 如何理解 '2006-01-02' 布局的含义?

go - 使用 Golang 与 hiveserver2 通信

go - 获取绑定(bind) : address already in use even after closing the connection in golang

sql - gorm 是否用逻辑 OR 解释结构体的内容?

json解码 key 类型

http - Go - http.Post 方法返回 400 Bad Request 而 http.Get 似乎工作

Go:无法呈现外部样式表

go - 如何忽略Go模板/文本中的元素