0

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 Answers 2

3

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"`
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yep that was the issue. Thanks for the mapping explanation!
0

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"`
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.