英文:
JSON decoding in golang
问题
所以我根据这里的示例尝试了一些代码,但没有得到任何数据,也没有错误。代码如下:
import (
"io"
"fmt"
"net/http"
"encoding/json"
)
type Credential struct {
username string `json:"username"`
password string `json:"password"`
}
func login(res http.ResponseWriter, req *http.Request) {
if req.Method == "POST" {
cred := Credential{}
err := json.NewDecoder(req.Body).Decode(&cred)
if err != nil {
panic("can't decode")
}
fmt.Println("credentials: " + cred.username + " , " + cred.password)
}
}
我使用以下命令进行测试:
curl -X POST -H "Accept: application/json" --data "{\"username\":\"x\",\"password\":\"y\"}" 127.0.0.1:8000/login -i
服务器打印出:
credentials: ,
为什么 cred.username 和 cred.password 中没有任何内容?
英文:
So I tried something based on the example here in my code, and get no data, but no error either. The code is:
import (
"io"
"fmt"
"net/http"
"encoding/json"
)
type Credential struct {
username string `json:"username"`
password string `json:"password"`
}
func login(res http.ResponseWriter, req *http.Request) {
if req.Method == "POST" {
cred := Credential{}
err := json.NewDecoder(req.Body).Decode(&cred)
if err != nil {
panic("can't decode")
}
fmt.Println("credentials: " + cred.username + " , " + cred.password)
}
}
I test with
> curl -X POST -H "Accept: application/json" --data "{"username":"x","password":"y"}" 127.0.0.1:8000/login -i
And the server prints out:
> credentials: ,
Why is there nothing in cred.username and cred.password?
答案1
得分: 4
Golang使用字段的首字母来声明该结构体的公有或私有性质。所以将username
改为Username
。
英文:
golang use first character of the field to declare public or private for that struct. so change username
to Username
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论