diff --git a/go.mod b/go.mod index 363c2564..922aab84 100644 --- a/go.mod +++ b/go.mod @@ -2,11 +2,9 @@ module github.com/sacloud/autoscaler go 1.21 -replace github.com/go-playground/validator/v10 => github.com/go-playground/validator/v10 v10.15.4 - require ( github.com/c-robinson/iplib v1.0.8 - github.com/go-playground/validator/v10 v10.16.0 + github.com/go-playground/validator/v10 v10.20.0 github.com/goccy/go-yaml v1.11.3 github.com/hashicorp/errwrap v1.1.0 github.com/hashicorp/go-multierror v1.1.1 diff --git a/go.sum b/go.sum index 7e62dc3d..9bd1999f 100644 --- a/go.sum +++ b/go.sum @@ -53,8 +53,8 @@ github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/o github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= -github.com/go-playground/validator/v10 v10.15.4 h1:zMXza4EpOdooxPel5xDqXEdXG5r+WggpvnAKMsalBjs= -github.com/go-playground/validator/v10 v10.15.4/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU= +github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8= +github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM= github.com/goccy/go-yaml v1.11.3 h1:B3W9IdWbvrUu2OYQGwvU1nZtvMQJPBKgBUuweJjLj6I= github.com/goccy/go-yaml v1.11.3/go.mod h1:wKnAMd44+9JAAnGQpWVEgBzGt3YuTaQ4uXoHvE4m7WU= github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE= diff --git a/validate/validate.go b/validate/validate.go index a76aa164..99d9583e 100644 --- a/validate/validate.go +++ b/validate/validate.go @@ -16,6 +16,8 @@ package validate import ( "fmt" + "log" + "net" "reflect" "strings" @@ -23,10 +25,9 @@ import ( "github.com/hashicorp/go-multierror" ) -var validatorInstance = validator.New() - -func validate(v interface{}) error { - validatorInstance.RegisterTagNameFunc(func(fld reflect.StructField) string { +var validatorInstance = func() *validator.Validate { + v := validator.New() + v.RegisterTagNameFunc(func(fld reflect.StructField) string { name := strings.SplitN(fld.Tag.Get("name"), ",", 2)[0] if name == "" { // nameタグがない場合はyamlタグを参照 @@ -37,6 +38,19 @@ func validate(v interface{}) error { } return name }) + if err := v.RegisterValidation("cidrv4", customCIDRv4Validator); err != nil { + log.Printf("Init validator failed: %s", err) + } + return v +}() + +// customCIDRv4Validator cidrv4をhttps://github.com/go-playground/validator/pull/945 以前の動作にするためのカスタムバリデーター +func customCIDRv4Validator(fl validator.FieldLevel) bool { + ip, _, err := net.ParseCIDR(fl.Field().String()) + return err == nil && ip.To4() != nil +} + +func validate(v interface{}) error { return validatorInstance.Struct(v) }