英文:
go struct JSON decode always empty return &{}
问题
在我的处理程序中,我可能做错了什么?
type Patient struct {
FirstName string
LastName string
}
func createHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
p := new(Patient)
err := json.NewDecoder(r.Body).Decode(&p)
if err != nil && err != io.EOF {
log.Fatal(err)
}
log.Print(p)
}
我总是从 curl -X POST $PATH -d '{"firstName": "Julian"}'
得到以下输出:
2016/01/23 17:33:50 &{ }
编辑
我添加了 fmt.Println(r)
并得到以下输出:
2016/01/23 18:33:22 &{POST /patients/ HTTP/1.1 1 1 map[Accept:[*/*] Content-Type:[application/json] User-Agent:[curl/7.46.0]] 0x9b2820 0 [] false localhost:8081 map[] map[] <nil> map[] [::1]:35394 /patients/ <nil> <nil>}
在调试了前一行之后,我意识到这是 gorilla 工具包的子路由问题。
英文:
What I can be doing wrong in my handler?
type Patient struct {
FirstName string
LastName string
}
func createHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
p := new(Patient)
err := json.NewDecoder(r.Body).Decode(&p)
if err != nil && err != io.EOF {
log.Fatal(err)
}
log.Print(p)
}
I always get from curl -X POST $PATH -d '{"firstName": "Julian"}'
2016/01/23 17:33:50 &{ }
Edit
I've added fmt.Println(r)
and got this
2016/01/23 18:33:22 &{POST /patients/ HTTP/1.1 1 1 map[Accept:[*/*] Content-Type:[application/json] User-Agent:[curl/7.46.0]] 0x9b2820 0 [] false localhost:8081 map[] map[] <nil> map[] [::1]:35394 /patients/ <nil> <nil>}
after debug the previous line I realized it's a problem with the subrouter of gorilla toolkit
答案1
得分: 1
两件事情:
由于您使用的是JSON库的约定,所以您的表单数据应该是FirstName
而不是firstName
。如果您真的想使用firstName
,您需要在字段上添加这个结构标签:json:"firstName"
。
接下来,您不再需要在&p
中放置&
,因为new(Patient)
已经返回一个指针。只需放置p
即可。
尽管个人而言,我会直接使用p := Patient{}
,这样我就知道它不是一个指针,并在解码器中使用&p
。
英文:
Two things:
Since you're using the JSON lib convention, then your post form data should be FirstName
and not firstName
. If you really wanted to use firstName
, you need to add this struct tag to the field: json:"firstName"
.
Next, you don't need to put &
in &p
anymore because new(Patient)
already returns a pointer. Just put p
.
Although personally, I'd just do p := Patient{}
just so I know it's not a pointer and use &p
in the decoder.
答案2
得分: 0
你需要移除r.ParseForm
。你可以在这里阅读更多信息:
https://golang.org/pkg/net/http/#Request.ParseForm
>对于POST或PUT请求,它还会解析请求体
因此,在调用ParseForm
之后,你的请求体将为空,并且你将收到一个空的结构体。
英文:
You have to remove the r.ParseForm
. You can read here
https://golang.org/pkg/net/http/#Request.ParseForm
>For POST or PUT requests, it also parses the request body
So your request body will be empty after the call of ParseForm
and you will receive an empty struct.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论