2017-06-12 09:04:52 +03:00
|
|
|
// Copyright 2017 Manu Martinez-Almeida. All rights reserved.
|
|
|
|
// Use of this source code is governed by a MIT style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
2015-05-31 17:18:50 +03:00
|
|
|
package binding
|
|
|
|
|
|
|
|
import (
|
|
|
|
"reflect"
|
|
|
|
"sync"
|
|
|
|
|
2019-09-05 16:39:56 +03:00
|
|
|
"gopkg.in/go-playground/validator.v9"
|
2015-05-31 17:18:50 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
type defaultValidator struct {
|
|
|
|
once sync.Once
|
|
|
|
validate *validator.Validate
|
|
|
|
}
|
|
|
|
|
|
|
|
var _ StructValidator = &defaultValidator{}
|
|
|
|
|
2018-07-01 16:10:48 +03:00
|
|
|
// ValidateStruct receives any kind of type, but only performed struct or pointer to struct type.
|
2015-05-31 17:18:50 +03:00
|
|
|
func (v *defaultValidator) ValidateStruct(obj interface{}) error {
|
2018-07-01 16:10:48 +03:00
|
|
|
value := reflect.ValueOf(obj)
|
|
|
|
valueType := value.Kind()
|
|
|
|
if valueType == reflect.Ptr {
|
|
|
|
valueType = value.Elem().Kind()
|
|
|
|
}
|
|
|
|
if valueType == reflect.Struct {
|
2015-05-31 17:18:50 +03:00
|
|
|
v.lazyinit()
|
2015-05-31 17:30:00 +03:00
|
|
|
if err := v.validate.Struct(obj); err != nil {
|
2018-07-01 16:10:48 +03:00
|
|
|
return err
|
2015-05-31 17:30:00 +03:00
|
|
|
}
|
2015-05-31 17:18:50 +03:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-03-29 09:33:07 +03:00
|
|
|
// Engine returns the underlying validator engine which powers the default
|
|
|
|
// Validator instance. This is useful if you want to register custom validations
|
|
|
|
// or struct level validations. See validator GoDoc for more info -
|
|
|
|
// https://godoc.org/gopkg.in/go-playground/validator.v8
|
|
|
|
func (v *defaultValidator) Engine() interface{} {
|
2017-08-27 10:37:39 +03:00
|
|
|
v.lazyinit()
|
2018-03-29 09:33:07 +03:00
|
|
|
return v.validate
|
2017-08-27 10:37:39 +03:00
|
|
|
}
|
|
|
|
|
2015-05-31 17:18:50 +03:00
|
|
|
func (v *defaultValidator) lazyinit() {
|
|
|
|
v.once.Do(func() {
|
2019-09-05 16:39:56 +03:00
|
|
|
v.validate = validator.New()
|
|
|
|
v.validate.SetTagName("binding")
|
2015-05-31 17:18:50 +03:00
|
|
|
})
|
|
|
|
}
|