尝试学习 golang,但我在验证中间件中使用 context.Request.Body
及其 struct
时迷失了
简单介绍一下它们是如何相互连接的,提前感谢您的帮助
我的中间件
package validations
import (
"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 entity
type 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": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b0d8d7d8f0d7ddd1d9dc9ed3dfdd" rel="noreferrer noopener nofollow">[email protected]</a>",
"password": "password",
"confirm_password": "password"
}
带有中间件的路由器
auth.POST("login", gin.Logger(), validations.SignupValidator, func(ctx *gin.Context) {
ctx.JSON(200, videoController.Save(ctx))
})
最佳答案
看起来您缺少返回
:
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()
。这是因为即使在您使用 c.Next()
写入 header (c.JSON()
) 后,gin 也会调用链中的下一个函数。
关于go - 如何验证来自中间件 go-gin 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62728768/