尝试学习 golang,我迷失在验证中间件中使用context.Request.Body它struct简要介绍它们如何相互连接,在此先感谢您的帮助我的中间件package validationsimport ( "github.com/bihire/ikaze_server_app/entity" "net/http" "github.com/gin-gonic/gin" "github.com/go-playground/validator/v10")func SignupValidator(c *gin.Context) { // user := c.Request.Body var user entity.User validate := validator.New() if err := validate.Struct(&user); err != nil { c.JSON(http.StatusBadRequest, gin.H{ "error": err.Error(), }) }}我的结构package entitytype User struct { Username string `json:"username" validate:"required"` Email string `json:"email" validate:"email"` Password string `json:"password" validate:"min=8,max=32,alphanum"` ConfirmPassword string `json:"confirm_password" validate:"eqfield=Password,required"`}返回响应错误{ "error": "Key: 'User.Username' Error:Field validation for 'Username' failed on the 'required' tag\nKey: 'User.Email' Error:Field validation for 'Email' failed on the 'email' tag\nKey: 'User.Password' Error:Field validation for 'Password' failed on the 'min' tag\nKey: 'User.ConfirmPassword' Error:Field validation for 'ConfirmPassword' failed on the 'required' tag"}{ "username": "bihire", "email": "hgh@gmail.com", "password": "password", "confirm_password": "password"}带中间件的路由器auth.POST("login", gin.Logger(), validations.SignupValidator, func(ctx *gin.Context) { ctx.JSON(200, videoController.Save(ctx)) })
1 回答
Qyouu
TA贡献1786条经验 获得超11个赞
看起来你错过了return:
func SignupValidator(c *gin.Context) gin.HandlerFunc {
return func(c *gin.Context) {
var user entity.User
if err := c.ShouldBindJSON(&user); err == nil {
validate := validator.New()
if err := validate.Struct(&user); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
c.Abort()
return
}
}
c.Next()
}
}
请注意,c.Abort()如果验证失败,我们会调用。这是因为 gin 调用链中的下一个函数,即使在您c.JSON()使用c.Next().
- 1 回答
- 0 关注
- 121 浏览
添加回答
举报
0/150
提交
取消