// @Tags 用户模块
// @Summary 登录
// @Produce json
// @Param info body models.Auth false "info"
// @Success 200 {object} app.Response
// @Failure 500 {object} app.Response
// @Router /api/v1/login [post]
func GetAuth(c *gin.Context) {
// appG := app.Gin{C: c}
// valid := validation.Validation{}
// user := make(map[string]string)
// c.BindJSON(&user)
// username := user["username"]
// password := util.EncodeMD5(user["password"])
// fmt.Println("password:", password)
// a := auth{Username: username, Password: password}
// ok, _ := valid.Valid(&a)
// appG.SuccessJson(nil)
c.JSON(200, nil)
return
}
在以上代码中,我把
// user := make(map[string]string)
// c.BindJSON(&user)
这两行注释掉后,此接口返回的状态码会变成400,不注释的话又是正常的。非常非常不解。。(刚学GO的菜鸟)
下面是相关的截图
2021-9-12更新
我发现c.BindJSON(&user)这个方法体里面调用了MustBindWith方法,它会返回异常状态码。
func (c *Context) MustBindWith(obj interface{}, b binding.Binding) error {
if err := c.ShouldBindWith(obj, b); err != nil {
c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) // nolint: errcheck
return err
}
return nil
}
类似的c.Bind方法也是如此。如果这样的话,不知大佬们是怎么避免入参校验错误时,仍返回200状态码的?(因为我希望状态码统一设为200,前端通过我JSON中给的code进行错误处理。)
问题已解决。
绑定结构体时使用ShouldBind系列方法
参考:https://www.cnblogs.com/Apale...