代码拉取完成,页面将自动刷新
package validator
import (
"gitee.com/wuzheng0709/backend-gopkg/infrastructure/pkg/gin/log"
"github.com/gin-gonic/gin/binding"
"github.com/go-playground/locales/zh"
ut "github.com/go-playground/universal-translator"
"github.com/go-playground/validator/v10"
zhTranslations "github.com/go-playground/validator/v10/translations/zh"
"reflect"
"sync"
)
var ReqValidator *validator.Validate
func init() {
ReqValidator = InitValidator()
}
// 替换gin的binding
func Init() {
valid := new(DefaultValidator)
binding.Validator = valid
}
type DefaultValidator struct {
once sync.Once
validate *myValidator
}
var _ binding.StructValidator = &DefaultValidator{}
func (v *DefaultValidator) ValidateStruct(obj interface{}) error {
if kindOfData(obj) == reflect.Struct {
v.lazyinit()
if err := v.validate.Validate(obj); err != nil {
return err[0]
}
}
return nil
}
func (v *DefaultValidator) Engine() interface{} {
v.lazyinit()
return v.validate
}
func (v *DefaultValidator) lazyinit() {
v.once.Do(func() {
v.validate = New()
v.validate.SetTag("binding")
v.validate.SetValidatorSplit("|")
// add any custom validations etc. here
})
}
func kindOfData(data interface{}) reflect.Kind {
value := reflect.ValueOf(data)
valueType := value.Kind()
if valueType == reflect.Ptr {
valueType = value.Elem().Kind()
}
return valueType
}
func InitValidator() *validator.Validate {
// validator
zhTranslator := zh.New()
universalTranslator := ut.New(zhTranslator, zhTranslator)
ReqValidator = validator.New()
translator, findTrans := universalTranslator.GetTranslator("zh")
if !findTrans {
log.Error("translator not found")
}
if errRegTrans := zhTranslations.RegisterDefaultTranslations(ReqValidator, translator); errRegTrans != nil {
log.Error(errRegTrans)
}
return ReqValidator
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。