来源:hgdjnet-server 9bfbafe10d417deea959bd53117bc88a10e60a83 项目身份 HKDJ / JHA-216,独立官网仓库,Jenkins 守卫键 hkdjnet 测试目录 /server/hkdj_net,App/Web API 30331/30332 Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
56 lines
938 B
Go
56 lines
938 B
Go
package v10
|
|
|
|
import (
|
|
"github.com/go-playground/validator/v10"
|
|
"reflect"
|
|
"sync"
|
|
|
|
"github.com/gin-gonic/gin/binding"
|
|
)
|
|
|
|
type DefaultValidator struct {
|
|
once sync.Once
|
|
validate *validator.Validate
|
|
}
|
|
|
|
var _ binding.StructValidator = &DefaultValidator{}
|
|
|
|
func (v *DefaultValidator) ValidateStruct(obj interface{}) error {
|
|
|
|
if kindOfData(obj) == reflect.Struct {
|
|
|
|
v.lazyinit()
|
|
|
|
if err := v.validate.Struct(obj); err != nil {
|
|
return error(err)
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (v *DefaultValidator) Engine() interface{} {
|
|
v.lazyinit()
|
|
return v.validate
|
|
}
|
|
|
|
func (v *DefaultValidator) lazyinit() {
|
|
v.once.Do(func() {
|
|
v.validate = validator.New()
|
|
v.validate.SetTagName("binding")
|
|
|
|
// 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
|
|
}
|