I am passing form data to a controller in Go. I have verified that the data is reaching the controller as its values appear in these variables:
emailValue := c.PostForm("email");
passwordValue := c.PostForm("password");
However, I am working from a boilerplate project to try to teach myself Go, and I am confused about some further processing included there. The "Invalid signin form" error always gets triggered in the following function:
func (ctrl UserController) Signin(c *gin.Context) {
var signinForm forms.SigninForm
if c.BindJSON(&signinForm) != nil {
c.JSON(406, gin.H{"message": "Invalid signin form", "form": signinForm})
c.Abort()
return
}
user, err := userModel.Signin(signinForm)
if err == nil {
session := sessions.Default(c)
session.Set("user_id", user.ID)
session.Set("user_email", user.Email)
session.Set("user_name", user.Name)
session.Save()
c.JSON(200, gin.H{"message": "User signed in", "user": user})
} else {
c.JSON(406, gin.H{"message": "Invalid signin details", "error": err.Error()})
}
}
I can't figure out from reading the docs and other Stack Overflow questions what exactly BindJSON is doing in a case like this. Here is the relevant struct
in the forms
file:
type SigninForm struct {
Email string `form:"email" json:"email" binding:"required,email"`
Password string `form:"password" json:"password" binding:"required"`
}
What is BindJSON
doing and how do I ensure that c.BindJSON(&signinForm) == nil
?