default_validator.go
This file
Path
binding/default_validator.go
98 lines · 2.3 KiB · Go
Last changed by
refactor: optimize error message concatenation in default_validator (#4685)wanghaolong613before adoptionc79f5d4
History of this fileTake it
1// Copyright 2017 Manu Martinez-Almeida. All rights reserved.2// Use of this source code is governed by a MIT style3// license that can be found in the LICENSE file.45package binding67import (8 "reflect"9 "strconv"10 "strings"11 "sync"1213 "github.com/go-playground/validator/v10"14)1516type defaultValidator struct {17 once sync.Once18 validate *validator.Validate19}2021type SliceValidationError []error2223// Error concatenates all error elements in SliceValidationError into a single string separated by \n.24func (err SliceValidationError) Error() string {25 if len(err) == 0 {26 return ""27 }2829 var b strings.Builder30 for i := range len(err) {31 if err[i] != nil {32 if b.Len() > 0 {33 b.WriteString("\n")34 }35 b.WriteString("[")36 b.WriteString(strconv.Itoa(i))37 b.WriteString("]: ")38 b.WriteString(err[i].Error())39 }40 }41 return b.String()42}4344var _ StructValidator = (*defaultValidator)(nil)4546// ValidateStruct receives any kind of type, but only performed struct or pointer to struct type.47func (v *defaultValidator) ValidateStruct(obj any) error {48 if obj == nil {49 return nil50 }5152 value := reflect.ValueOf(obj)53 switch value.Kind() {54 case reflect.Ptr:55 if value.Elem().Kind() != reflect.Struct {56 return v.ValidateStruct(value.Elem().Interface())57 }58 return v.validateStruct(obj)59 case reflect.Struct:60 return v.validateStruct(obj)61 case reflect.Slice, reflect.Array:62 count := value.Len()63 validateRet := make(SliceValidationError, 0)64 for i := range count {65 if err := v.ValidateStruct(value.Index(i).Interface()); err != nil {66 validateRet = append(validateRet, err)67 }68 }69 if len(validateRet) == 0 {70 return nil71 }72 return validateRet73 default:74 return nil75 }76}7778// validateStruct receives struct type79func (v *defaultValidator) validateStruct(obj any) error {80 v.lazyinit()81 return v.validate.Struct(obj)82}8384// Engine returns the underlying validator engine which powers the default85// Validator instance. This is useful if you want to register custom validations86// or struct level validations. See validator GoDoc for more info -87// https://pkg.go.dev/github.com/go-playground/validator/v1088func (v *defaultValidator) Engine() any {89 v.lazyinit()90 return v.validate91}9293func (v *defaultValidator) lazyinit() {94 v.once.Do(func() {95 v.validate = validator.New()96 v.validate.SetTagName("binding")97 })98}