JSON 解码器无法处理 http 请求正文
JSON decoder not working on http request body
我开始疯狂地尝试让 Go 解码这个 json 请求正文。这是一个示例请求:
curl -X POST -d "{\"username\":\"foo\", \"password\":\"bar\"}" http://localhost:3000/users
这是我的处理程序:
mux.HandleFunc("/users", func(rw http.ResponseWriter, req *http.Request) {
var body struct {
username string
password string
}
// buf := make([]byte, req.ContentLength)
// req.Body.Read(buf)
// fmt.Println(string(buf))
//
// The above commented out code will correctly print:
// {"username":"foo", "password":"bar"}
err := json.NewDecoder(req.Body).Decode(&body)
if err != nil {
rw.WriteHeader(http.StatusNotAcceptable)
return
}
fmt.Printf("%+v\n", body)
// prints -> {username: password:}
})
正如评论所暗示的那样,我可以验证 req.Body
确实是正确的——但无论出于何种原因,json.NewDecoder(req.Body).Decode(&body)
从未填写 body
的字段。
如有任何帮助,我们将不胜感激!
问题是 json 解码器不处理私有结构字段。 body
结构中的字段是私有的。
像这样重写它就可以了:
var body struct {
Username string `json:"username"`
Password string `json:"password"`
}
基本上,json:"username"
是一种告诉 json 解码器如何将对象的 json 名称映射到结构名称的方法。在这种情况下,仅用于解码,没有必要 - json 解码器足够智能,可以翻译 upper/lower 案例。
但是,如果您也使用该对象对 json 进行编码,则需要它,否则在结果 json.
中会有大写字段名称
您可以使用 json 结构标签做一些更有用的事情,比如从编码的 json 中省略空字段,或者完全跳过字段。
您可以在 json.Marshal
的文档中阅读有关 JSON 结构标签的更多信息:http://golang.org/pkg/encoding/json/#Marshal
我开始疯狂地尝试让 Go 解码这个 json 请求正文。这是一个示例请求:
curl -X POST -d "{\"username\":\"foo\", \"password\":\"bar\"}" http://localhost:3000/users
这是我的处理程序:
mux.HandleFunc("/users", func(rw http.ResponseWriter, req *http.Request) {
var body struct {
username string
password string
}
// buf := make([]byte, req.ContentLength)
// req.Body.Read(buf)
// fmt.Println(string(buf))
//
// The above commented out code will correctly print:
// {"username":"foo", "password":"bar"}
err := json.NewDecoder(req.Body).Decode(&body)
if err != nil {
rw.WriteHeader(http.StatusNotAcceptable)
return
}
fmt.Printf("%+v\n", body)
// prints -> {username: password:}
})
正如评论所暗示的那样,我可以验证 req.Body
确实是正确的——但无论出于何种原因,json.NewDecoder(req.Body).Decode(&body)
从未填写 body
的字段。
如有任何帮助,我们将不胜感激!
问题是 json 解码器不处理私有结构字段。 body
结构中的字段是私有的。
像这样重写它就可以了:
var body struct {
Username string `json:"username"`
Password string `json:"password"`
}
基本上,json:"username"
是一种告诉 json 解码器如何将对象的 json 名称映射到结构名称的方法。在这种情况下,仅用于解码,没有必要 - json 解码器足够智能,可以翻译 upper/lower 案例。
但是,如果您也使用该对象对 json 进行编码,则需要它,否则在结果 json.
中会有大写字段名称您可以使用 json 结构标签做一些更有用的事情,比如从编码的 json 中省略空字段,或者完全跳过字段。
您可以在 json.Marshal
的文档中阅读有关 JSON 结构标签的更多信息:http://golang.org/pkg/encoding/json/#Marshal