我正在尝试创建一个公共的HTTP请求验证器中间件函数,它接受类型(可能是reflect.Type)作为参数,然后使用包github.com/go-playground/validator/v10将JSON解锁为上述类型的结构并验证结构。我试着用下面的示例代码来解释.
示例
type LoginRequestBody struct {
Username string `json:"username",validate:"required"`
Password string `json:"password",validate:"required"`
}
type SignupReqBody struct {
Username string `json:"username",validate:"required"`
Password string `json:"password",validate:"required"`
Age int `json:"age",validate:"required"`
}
// sample routers with a common middleware validator function
router.POST("/login", ReqValidate("LoginRequestBody"), LoginController)
router.POST("/signup", ReqValidate("SignupReqBody"), SignupController)
func ReqValidate(<something>) gin.HandlerFunc {
return func (c *gin.Context) {
// unmarshalling JSON into a struct
// common validation logic...
c.Next()
}
}总的来说,我希望实现与使用Joi的Node.js中相同的验证器灵活性。
发布于 2022-11-01 18:19:04
我不知道是否有必要使用中间件,但我最近尝试做一些事情,我发现了一个很好的教程,您可以看到这里。
对于Gin,您可以使用绑定:
示例:
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
type AnyStruct struct {
Price uint `json:"price" binding:"required,gte=10,lte=1000"`
}
func main() {
engine:=gin.New()
engine.POST("/test", func(context *gin.Context) {
body:=AnyStruct{}
if err:=context.ShouldBindJSON(&body);err!=nil{
context.AbortWithStatusJSON(http.StatusBadRequest,
gin.H{
"error": "VALIDATEERR-1",
"message": "Invalid inputs. Please check your inputs"})
return
}
context.JSON(http.StatusAccepted,&body)
})
engine.Run(":3000")
}发布于 2022-11-01 18:29:06
不要用逗号分隔结构标签键值对,使用空格。
您可以使用泛型(类型参数)替换<something>,但是控制器需要有具体的类型作为参数。
例如:
func ReqValidate[T any](next func(*gin.Context, *T)) gin.HandlerFunc {
return func(c *gin.Context) {
params := new(T)
if err := c.ShouldBindJSON(params); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
next(c, params)
}
}然后调度员:
type LoginRequestBody struct {
Username string `json:"username" validate:"required"`
Password string `json:"password" validate:"required"`
}
func LoginController(c *gin.Context, params *LoginRequestBody) {
// ...
}
type SignupReqBody struct {
Username string `json:"username" validate:"required"`
Password string `json:"password" validate:"required"`
Age int `json:"age" validate:"required"`
}
func SignupController(c *gin.Context, params *SignupReqBody) {
// ...
}然后路由:
router := gin.Default()
router.POST("/login", ReqValidate(LoginController))
router.POST("/signup", ReqValidate(SignupController))https://stackoverflow.com/questions/74279976
复制相似问题