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 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?