2 回答
TA贡献1804条经验 获得超8个赞
您必须首先导出它,signupValidation因为它在另一个包上。为此,只需更改为大写:SignupValidation
package validations
import (
"github.com/bihire/ikaze_server_app/entity"
"net/http"
"github.com/gin-gonic/gin"
"gopkg.in/validator.v2"
)
func SignupValidator(ctx *gin.Context) {
var user entity.User
// if err := ctx.ShouldBindJSON(&user); err != nil {
// ctx.JSON(http.StatusBadRequest, gin.H{
// "error": err.Error(),
// })
// }
if err := validator.Validate(user); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
}
}
第二:用这个签名制作一个 gin 中间件func (ctx *gin.Context)。您可以通过两种方式进行:
首先,如果您不想更改注册
package routes
import (
"github.com/gin-gonic/gin"
"github.com/bihire/ikaze_server_app/service"
"github.com/bihire/ikaze_server_app/controller"
"github.com/bihire/ikaze_server_app/validations"
)
var (
userController controller.UserController = controller.New(UserService)
)
func Routes(route *gin.Engine) {
auth := route.Group("/api/auth")
{
auth.POST("login", gin.Logger(), validations.SignupValidator, func(ctx *gin.Context) {
ctx.JSON(200, userController.Save(ctx))
})
}
}
或者,更改注册:
func SignupValidator(ctx *gin.Context) gin.HandlerFunc {
return func(c *gin.Context) {
var user entity.User
// if err := ctx.ShouldBindJSON(&user); err != nil {
// ctx.JSON(http.StatusBadRequest, gin.H{
// "error": err.Error(),
// })
// }
if err := validator.Validate(user); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
return
}
c.Next()
}
}
然后,您可以使用validations.signupValidator()
在此处查看示例:https ://github.com/gin-gonic/gin#custom-middleware
- 2 回答
- 0 关注
- 136 浏览
添加回答
举报