default_validator.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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) RegisterValidation(key string, fn validator.Func) error {
  25. v.lazyinit()
  26. return v.validate.RegisterValidation(key, fn)
  27. }
  28. func (v *defaultValidator) lazyinit() {
  29. v.once.Do(func() {
  30. config := &validator.Config{TagName: "binding"}
  31. v.validate = validator.New(config)
  32. })
  33. }
  34. func kindOfData(data interface{}) reflect.Kind {
  35. value := reflect.ValueOf(data)
  36. valueType := value.Kind()
  37. if valueType == reflect.Ptr {
  38. valueType = value.Elem().Kind()
  39. }
  40. return valueType
  41. }