default_validator.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Copyright 2017 Manu Martinez-Almeida. All rights reserved.
  2. // Use of this source code is governed by a MIT style
  3. // license that can be found in the LICENSE file.
  4. package binding
  5. import (
  6. "reflect"
  7. "sync"
  8. "gopkg.in/go-playground/validator.v9"
  9. )
  10. type defaultValidator struct {
  11. once sync.Once
  12. validate *validator.Validate
  13. }
  14. var _ StructValidator = &defaultValidator{}
  15. // ValidateStruct receives any kind of type, but only performed struct or pointer to struct type.
  16. func (v *defaultValidator) ValidateStruct(obj interface{}) error {
  17. value := reflect.ValueOf(obj)
  18. valueType := value.Kind()
  19. if valueType == reflect.Ptr {
  20. valueType = value.Elem().Kind()
  21. }
  22. if valueType == reflect.Struct {
  23. v.lazyinit()
  24. if err := v.validate.Struct(obj); err != nil {
  25. return err
  26. }
  27. }
  28. return nil
  29. }
  30. // Engine returns the underlying validator engine which powers the default
  31. // Validator instance. This is useful if you want to register custom validations
  32. // or struct level validations. See validator GoDoc for more info -
  33. // https://godoc.org/gopkg.in/go-playground/validator.v8
  34. func (v *defaultValidator) Engine() interface{} {
  35. v.lazyinit()
  36. return v.validate
  37. }
  38. func (v *defaultValidator) lazyinit() {
  39. v.once.Do(func() {
  40. v.validate = validator.New()
  41. v.validate.SetTagName("binding")
  42. })
  43. }