douyan7916 2018-02-21 17:47
浏览 318
已采纳

如何在Golang中绑定JSON

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?

  • 写回答

1条回答 默认 最新

  • douman9420 2018-02-21 18:17
    关注

    I may be misunderstanding here, but if your content is available in PostForm calls then I would assume the Content-Type is not application/json but probably application/x-www-form-urlencoded. If that is the case, then using BindJSON won't work as it is trying to bind the post data to the struct defined by parsing the post data as json. I think this might work:

    if err := c.ShouldBindWith(&signinForm, binding.Form); err != nil {
       c.JSON(406, gin.H{"message": "Invalid signin form", "form": signinForm})
       c.Abort()
       return
    }
    

    The alternative would be to actually send your post data as json similar to:

    {"email": "test@example.com", "password": "pass"}
    

    And make sure the Content-Type header is application/json

    I have never used Gin, so this may be completely wrong.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题