OSDN Git Service

new repo
[bytom/vapor.git] / vendor / gopkg.in / go-playground / validator.v9 / _examples / gin-upgrading-overriding / v8_to_v9.go
1 package main
2
3 import (
4         "reflect"
5         "sync"
6
7         "github.com/gin-gonic/gin/binding"
8         "gopkg.in/go-playground/validator.v9"
9 )
10
11 type defaultValidator struct {
12         once     sync.Once
13         validate *validator.Validate
14 }
15
16 var _ binding.StructValidator = &defaultValidator{}
17
18 func (v *defaultValidator) ValidateStruct(obj interface{}) error {
19
20         if kindOfData(obj) == reflect.Struct {
21
22                 v.lazyinit()
23
24                 if err := v.validate.Struct(obj); err != nil {
25                         return error(err)
26                 }
27         }
28
29         return nil
30 }
31
32 func (v *defaultValidator) lazyinit() {
33         v.once.Do(func() {
34                 v.validate = validator.New()
35                 v.validate.SetTagName("binding")
36
37                 // add any custom validations etc. here
38         })
39 }
40
41 func kindOfData(data interface{}) reflect.Kind {
42
43         value := reflect.ValueOf(data)
44         valueType := value.Kind()
45
46         if valueType == reflect.Ptr {
47                 valueType = value.Elem().Kind()
48         }
49         return valueType
50 }