service/library/middleware/validator.go

55 lines
1.2 KiB
Go

package middleware
import (
"fmt"
"reflect"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"service/api/base"
"service/library/validator"
)
func JSONParamValidator(p interface{}) gin.HandlerFunc {
return func(ctx *gin.Context) {
v := reflect.New(reflect.TypeOf(p))
err := ctx.ShouldBindBodyWith(v.Interface(), binding.JSON)
if !base.CheckBadRequest(ctx, err) {
return
}
//非空校验
if notNullItem, ok := v.Interface().(validator.NotNullItem); ok {
err := validator.GetDefaultNotNullValidator().Validate(notNullItem)
if err != nil {
base.CheckBadRequest(ctx, fmt.Errorf("非空校验失败: %v", err))
}
}
ctx.Set("client_req", v.Interface())
ctx.Next()
}
}
func FORMParamValidator(p interface{}) gin.HandlerFunc {
return func(ctx *gin.Context) {
v := reflect.New(reflect.TypeOf(p))
err := ctx.ShouldBindWith(v.Interface(), binding.Form)
if !base.CheckBadRequest(ctx, err) {
return
}
//非空校验
if notNullItem, ok := v.Interface().(validator.NotNullItem); ok {
err := validator.GetDefaultNotNullValidator().Validate(notNullItem)
if err != nil {
base.CheckBadRequest(ctx, fmt.Errorf("非空校验失败: %v", err))
}
}
ctx.Set("client_req", v.Interface())
ctx.Next()
}
}