英文:
How to Decode & Map JSON Objects using NewDecode, Golang and req *http.Request
问题
来自PHP的我是一个完全的Golang新手。我读到一个非常类似于我的问题的问题,但我的实现有些不同。每当我使用以下代码进行解码时,变量msg.Username总是为空。Golang在这里不会抛出错误,所以我知道我在这里漏掉了一些非常小但非常重要的东西,但我不知道是什么。我非常感谢任何帮助,并且当然期望这是一个恍然大悟的时刻。谢谢!
//我要发送到本地服务器的JSON是
//{"company_domain":"example.com", "user_name":"testu","password":"testpw"}
func Login(w http.ResponseWriter, req *http.Request) {
type Message struct {
CompanyDomain string
Username string
Password string
}
//解码
var msg Message
decoder := json.NewDecoder(req.Body)
err := decoder.Decode(&msg)
if err != nil {
err.Error())
}
w.Write([]byte(msg.Username))// <- 这个打印语句总是为空
authorize, err := models.VerifyAuth(msg.Username, msg.Password, msg.CompanyDomain, w)
if err != nil {
err.Error())
}
...
英文:
Coming from PHP I'm a TOTAL Golang newb here. I read a question that is VERY similar to mine but my implementation is slightly off. Whenever I go to decode using the following code the variable msg.Username is always blank. Golang doesn't throw errors here so I know I'm missing something super small here and very important but I have no idea what it could be. I would be a very appreciative of any help and am of course expecting this to be a fist-to-foerhead epiphany. Thanks!
//The JSON I'm posting to my local server is
//{"company_domain":"example.com", "user_name":"testu","password":"testpw"}
func Login(w http.ResponseWriter, req *http.Request) {
type Message struct {
CompanyDomain string
Username string
Password string
}
//decode
var msg Message
decoder := json.NewDecoder(req.Body)
err := decoder.Decode(&msg)
if err != nil {
err.Error())
}
w.Write([]byte(msg.Username))// <- This print statement always comes in blank
authorize, err := models.VerifyAuth(msg.Username, msg.Password, msg.CompanyDomain, w)
if err != nil {
err.Error())
}
...
答案1
得分: 3
给你的结构字段打上标签,这样解码器就知道如何将 JSON 键映射到你的结构体。
type Message struct {
CompanyDomain string `json:"company_domain"`
Username string `json:"user_name"`
Password string `json:"password"`
}
英文:
Tag your struct fields so the decoder knows how to map the json keys to your struct.
type Message struct {
CompanyDomain string `json:"company_domain"`
Username string `json:"user_name"`
Password string `json:"password"`
}
答案2
得分: 0
你只需要在你的结构体中添加json:"field_name"
:
type Message struct {
CompanyDomain string `json:"company_domain"`
Username string `json:"user_name"`
Password string `json:"password"`
}
英文:
You just need to add json:"field_name"
to your struct:
type Message struct {
CompanyDomain string `json:"company_domain"`
Username string `json:"user_name"`
Password string `json:"password"`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论