default_validator.go 949 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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.v8"
  9. )
  10. type defaultValidator struct {
  11. once sync.Once
  12. validate *validator.Validate
  13. }
  14. var _ StructValidator = &defaultValidator{}
  15. func (v *defaultValidator) ValidateStruct(obj interface{}) error {
  16. if kindOfData(obj) == reflect.Struct {
  17. v.lazyinit()
  18. if err := v.validate.Struct(obj); err != nil {
  19. return error(err)
  20. }
  21. }
  22. return nil
  23. }
  24. func (v *defaultValidator) lazyinit() {
  25. v.once.Do(func() {
  26. config := &validator.Config{TagName: "binding"}
  27. v.validate = validator.New(config)
  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. }