asaskevich / govalidator

[Go] Package of validators and sanitizers for strings, numerics, slices and structs
MIT License
6.05k stars 555 forks source link

fatal error: concurrent map writes #485

Open mycode65678 opened 1 year ago

mycode65678 commented 1 year ago

The gin framework I use will cause fatal errors when there are too many concurrent accesses.

fatal error: concurrent map writes


// implements the binding.StructValidator
type customValidator struct{}

func (c *customValidator) ValidateStruct(ptr interface{}) error {

    govalidator.ParamTagMap["google"] = govalidator.ParamValidator(func(str string, params ...string) bool {
        a.Log.Debug("customGoogle ParamTagMap")
        return false
    })
    govalidator.ParamTagMap["google"] = govalidator.ParamValidator(func(str string, params ...string) bool {
        a.Log.Debug("customGoogle ParamTagMap")
        return false
    })

    // Add your own struct validation tags with parameter
    govalidator.ParamTagMap["compared"] = govalidator.ParamValidator(func(str string, params ...string) bool {
        res := reflect.ValueOf(ptr).Elem().FieldByName(params[0]).Interface().(string)
        return str == res
    })

    //register the regex for validate
    govalidator.ParamTagRegexMap["compared"] = regexp.MustCompile("^compared\\((\\w+)\\)$")
    if _, err := govalidator.ValidateStruct(ptr); err != nil {
        a.Log.Errorf("ValidateStruct err:%v", err)
        return err
    }
    return nil
}

func (c *customValidator) Engine() interface{} {
    return nil
}

func main(){
    binding.Validator = &customValidator{}
        r := gin.Default()
    r.Run(":9191")
}