...

Source file src/github.com/go-playground/validator/v10/_examples/gin-upgrading-overriding/v8_to_v9.go

Documentation: github.com/go-playground/validator/v10/_examples/gin-upgrading-overriding

     1  package main
     2  
     3  import (
     4  	"reflect"
     5  	"sync"
     6  
     7  	"github.com/gin-gonic/gin/binding"
     8  	"github.com/go-playground/validator/v10"
     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 err
    26  		}
    27  	}
    28  
    29  	return nil
    30  }
    31  
    32  func (v *defaultValidator) Engine() interface{} {
    33  	v.lazyinit()
    34  	return v.validate
    35  }
    36  
    37  func (v *defaultValidator) lazyinit() {
    38  	v.once.Do(func() {
    39  		v.validate = validator.New()
    40  		v.validate.SetTagName("binding")
    41  
    42  		// add any custom validations etc. here
    43  	})
    44  }
    45  
    46  func kindOfData(data interface{}) reflect.Kind {
    47  
    48  	value := reflect.ValueOf(data)
    49  	valueType := value.Kind()
    50  
    51  	if valueType == reflect.Ptr {
    52  		valueType = value.Elem().Kind()
    53  	}
    54  	return valueType
    55  }
    56  

View as plain text