diff --git a/config/config.go b/config/config.go index 2479fbf7..49bd2cdb 100644 --- a/config/config.go +++ b/config/config.go @@ -2,6 +2,7 @@ package config import ( "bytes" + "errors" "fmt" "io" "os" @@ -9,6 +10,7 @@ import ( "strings" "text/template" + "github.com/go-playground/validator/v10" "github.com/mitchellh/mapstructure" "github.com/spf13/viper" ) @@ -181,8 +183,7 @@ func evaluateConfigWithEnv(configFile io.Reader, writers ...io.Writer) (io.Reade return nil, fmt.Errorf("unable to read the config file: %w", err) } - // t := template.New("appConfigTemplate").Option("missingkey=zero") - t := template.New("appConfigTemplate") + t := template.New("appConfigTemplate").Option("missingkey=zero") tmpl, err := t.Parse(string(b)) if err != nil { return nil, fmt.Errorf("unable to parse template from: \n%s: %w", string(b), err) @@ -205,3 +206,17 @@ func getAppEnv() string { } return env } + +func validateConfiguration[T any](cfg *T) error { + validate := validator.New() + err := validate.Struct(*cfg) + fmt.Println("...validateConfiguration, cfg:", cfg) + fmt.Println("...validateConfiguration, err:", err) + if err != nil { + errSlice := &validator.ValidationErrors{} + errors.As(err, errSlice) + return errSlice + } + + return nil +} diff --git a/config/config_test.go b/config/config_test.go index 595d9ebc..fce3f720 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -38,7 +38,6 @@ blah2=test2` b, err := io.ReadAll(eval) r.NoError(err) r.Equal(expected, string(b)) - r.Equal(true, false) } func TesEvaluateConfigWithMissingEnv(t *testing.T) { diff --git a/config/validation.go b/config/validation.go deleted file mode 100644 index 8fd613c6..00000000 --- a/config/validation.go +++ /dev/null @@ -1,49 +0,0 @@ -package config - -import ( - "errors" - "fmt" - "reflect" - - "github.com/go-playground/validator/v10" -) - -// var ( -// once sync.Once -// validate *validator.Validate -// ) - -// func init() { -// once.Do(func() { -// validate = validator.New() -// }) -// } - -func validateConfiguration[T any](cfg *T) error { - var errs []ValidationError - // var finalErr error = nil - - validate := validator.New() - err := validate.Struct(cfg) - if err != nil { - errSlice := &validator.ValidationErrors{} - errors.As(err, errSlice) - for _, err := range *errSlice { - var element ValidationError - field, _ := reflect.ValueOf(cfg).Type().FieldByName(err.Field()) - element.FailedField = field.Tag.Get("json") - if element.FailedField == "" { - element.FailedField = field.Tag.Get("query") - } - element.Tag = err.Tag() - element.Value = err.Param() - element.Type = err.Kind().String() - element.Message = fmt.Sprintf("Field validation for '%s' failed on the '%s' tag", element.FailedField, element.Tag) - - errs = append(errs, element) - } - return errSlice - } - - return nil -}