default_validator.go 867 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package binding
  2. import (
  3. "reflect"
  4. "sync"
  5. "gopkg.in/go-playground/validator.v9"
  6. )
  7. type defaultValidator struct {
  8. once sync.Once
  9. validate *validator.Validate
  10. }
  11. var _ StructValidator = &defaultValidator{}
  12. func (v *defaultValidator) ValidateStruct(obj interface{}) error {
  13. if kindOfData(obj) == reflect.Struct {
  14. v.lazyinit()
  15. if err := v.validate.Struct(obj); err != nil {
  16. return err
  17. }
  18. }
  19. return nil
  20. }
  21. func (v *defaultValidator) RegisterValidation(key string, fn validator.Func) error {
  22. v.lazyinit()
  23. return v.validate.RegisterValidation(key, fn)
  24. }
  25. func (v *defaultValidator) lazyinit() {
  26. v.once.Do(func() {
  27. v.validate = validator.New()
  28. })
  29. }
  30. func kindOfData(data interface{}) reflect.Kind {
  31. value := reflect.ValueOf(data)
  32. valueType := value.Kind()
  33. if valueType == reflect.Ptr {
  34. valueType = value.Elem().Kind()
  35. }
  36. return valueType
  37. }