2017-06-12 06:04:52 +00: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 14:18:50 +00:00
|
|
|
package binding
|
|
|
|
|
|
|
|
import (
|
|
|
|
"reflect"
|
|
|
|
"sync"
|
|
|
|
|
2016-01-26 18:28:26 +00:00
|
|
|
"gopkg.in/go-playground/validator.v8"
|
2015-05-31 14:18:50 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type defaultValidator struct {
|
|
|
|
once sync.Once
|
|
|
|
validate *validator.Validate
|
|
|
|
}
|
|
|
|
|
|
|
|
var _ StructValidator = &defaultValidator{}
|
|
|
|
|
|
|
|
func (v *defaultValidator) ValidateStruct(obj interface{}) error {
|
|
|
|
if kindOfData(obj) == reflect.Struct {
|
|
|
|
v.lazyinit()
|
2015-05-31 14:30:00 +00:00
|
|
|
if err := v.validate.Struct(obj); err != nil {
|
|
|
|
return error(err)
|
|
|
|
}
|
2015-05-31 14:18:50 +00:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (v *defaultValidator) lazyinit() {
|
|
|
|
v.once.Do(func() {
|
2016-01-26 18:28:26 +00:00
|
|
|
config := &validator.Config{TagName: "binding"}
|
|
|
|
v.validate = validator.New(config)
|
2015-05-31 14:18:50 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func kindOfData(data interface{}) reflect.Kind {
|
|
|
|
value := reflect.ValueOf(data)
|
|
|
|
valueType := value.Kind()
|
|
|
|
if valueType == reflect.Ptr {
|
|
|
|
valueType = value.Elem().Kind()
|
|
|
|
}
|
|
|
|
return valueType
|
|
|
|
}
|