如何正确处理Go中的JSON POST请求?
大家好!我刚开始学习Go,正在编写一个简单的REST API服务器。在处理POST请求中的JSON时遇到了问题。
我有一个User结构体:
```go
type User struct {
Name string
Age int
}
```
以及一个handler:
```go
func createUser(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var user User
err := json.NewDecoder(r.Body).Decode(&user)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
fmt.Fprintf(w, "User: %+v", user)
}
```
当我通过curl发送POST请求时:
```
curl -X POST -H "Content-Type: application/json" -d '{"name":"John","age":30}' http://localhost:8080/user
```
我得到一个空对象:`User: {Name: Age:0}`。我哪里做错了?为什么字段没有被填充?我检查过请求体确实到达了——如果我将r.Body作为字符串输出,