douzheng5717 2015-11-23 20:35
浏览 156
已采纳

如何使用NewDecode,Golang和req * http.Request解码和映射JSON对象

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())
  }
  ...
  • 写回答

2条回答 默认 最新

  • doutuoben6908 2015-11-23 20:37
    关注

    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"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?