default_validator.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. "bytes"
  7. "errors"
  8. "fmt"
  9. "reflect"
  10. "sync"
  11. "gopkg.in/go-playground/validator.v8"
  12. )
  13. type defaultValidator struct {
  14. once sync.Once
  15. validate *validator.Validate
  16. }
  17. var _ StructValidator = &defaultValidator{}
  18. func (v *defaultValidator) ValidateStruct(obj interface{}) error {
  19. if kindOfData(obj) == reflect.Struct {
  20. v.lazyinit()
  21. if err := v.validate.Struct(obj); err != nil {
  22. buf := bytes.NewBufferString("")
  23. for _, v := range err.(validator.ValidationErrors) {
  24. buf.WriteString(fmt.Sprintf("%s %s %s", v.Name, v.Tag, v.Param))
  25. buf.WriteString(";")
  26. }
  27. return errors.New(buf.String()) //error(err)
  28. }
  29. }
  30. return nil
  31. }
  32. func (v *defaultValidator) RegisterValidation(key string, fn validator.Func) error {
  33. v.lazyinit()
  34. return v.validate.RegisterValidation(key, fn)
  35. }
  36. func (v *defaultValidator) lazyinit() {
  37. v.once.Do(func() {
  38. config := &validator.Config{TagName: "validate"}
  39. v.validate = validator.New(config)
  40. })
  41. }
  42. func kindOfData(data interface{}) reflect.Kind {
  43. value := reflect.ValueOf(data)
  44. valueType := value.Kind()
  45. if valueType == reflect.Ptr {
  46. valueType = value.Elem().Kind()
  47. }
  48. return valueType
  49. }