default_validator.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. // Engine returns the underlying validator engine which powers the default
  25. // Validator instance. This is useful if you want to register custom validations
  26. // or struct level validations. See validator GoDoc for more info -
  27. // https://godoc.org/gopkg.in/go-playground/validator.v8
  28. func (v *defaultValidator) Engine() interface{} {
  29. v.lazyinit()
  30. return v.validate
  31. }
  32. func (v *defaultValidator) lazyinit() {
  33. v.once.Do(func() {
  34. config := &validator.Config{TagName: "binding"}
  35. v.validate = validator.New(config)
  36. })
  37. }
  38. func kindOfData(data interface{}) reflect.Kind {
  39. value := reflect.ValueOf(data)
  40. valueType := value.Kind()
  41. if valueType == reflect.Ptr {
  42. valueType = value.Elem().Kind()
  43. }
  44. return valueType
  45. }