lazyInit initialize the validate Settings, no need to use sync.once

This commit is contained in:
daheige 2021-07-14 22:57:08 +08:00
parent b68a761dc9
commit 12d66f7345
1 changed files with 6 additions and 7 deletions

View File

@ -8,13 +8,11 @@ import (
"fmt" "fmt"
"reflect" "reflect"
"strings" "strings"
"sync"
"github.com/go-playground/validator/v10" "github.com/go-playground/validator/v10"
) )
type defaultValidator struct { type defaultValidator struct {
once sync.Once
validate *validator.Validate validate *validator.Validate
} }
@ -76,7 +74,7 @@ func (v *defaultValidator) ValidateStruct(obj interface{}) error {
// validateStruct receives struct type // validateStruct receives struct type
func (v *defaultValidator) validateStruct(obj interface{}) error { func (v *defaultValidator) validateStruct(obj interface{}) error {
v.lazyinit() v.lazyInit()
return v.validate.Struct(obj) return v.validate.Struct(obj)
} }
@ -85,13 +83,14 @@ func (v *defaultValidator) validateStruct(obj interface{}) error {
// or struct level validations. See validator GoDoc for more info - // or struct level validations. See validator GoDoc for more info -
// https://pkg.go.dev/github.com/go-playground/validator/v10 // https://pkg.go.dev/github.com/go-playground/validator/v10
func (v *defaultValidator) Engine() interface{} { func (v *defaultValidator) Engine() interface{} {
v.lazyinit() v.lazyInit()
return v.validate return v.validate
} }
func (v *defaultValidator) lazyinit() { // lazyInit initialize the validate Settings, no need to use sync.once
v.once.Do(func() { func (v *defaultValidator) lazyInit() {
if v.validate == nil {
v.validate = validator.New() v.validate = validator.New()
v.validate.SetTagName("binding") v.validate.SetTagName("binding")
}) }
} }