default_validator.go 1.3 KB

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