diff --git a/config/config.go b/config/config.go index bb5beef7..324fbbde 100644 --- a/config/config.go +++ b/config/config.go @@ -5,6 +5,8 @@ import ( "io" "io/fs" "os" + "reflect" + "regexp" "strings" "github.com/moov-io/base/log" @@ -125,4 +127,14 @@ func LoadEnvironmentFile(logger log.Logger, envVar string, v *viper.Viper) error func overwriteConfig(cfg *mapstructure.DecoderConfig) { cfg.ErrorUnused = true cfg.ZeroFields = true + + cfg.DecodeHook = func(t1 reflect.Type, t2 reflect.Type, value interface{}) (interface{}, error) { + decodingRegex := t2.String() == "regexp.Regexp" + if decodingRegex { + if stringValue, ok := value.(string); ok { + return regexp.Compile(stringValue) + } + } + return value, nil + } } diff --git a/config/config_test.go b/config/config_test.go index 8e71c7eb..6b7c7b17 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -2,6 +2,7 @@ package config_test import ( "path/filepath" + "regexp" "testing" "github.com/moov-io/base" @@ -22,6 +23,8 @@ type ConfigModel struct { Zero string Widgets map[string]Widget + + Search SearchConfig } type Widget struct { @@ -47,6 +50,10 @@ type Nested3 struct { Value string } +type SearchConfig struct { + Patterns []*regexp.Regexp +} + func Test_Load(t *testing.T) { t.Setenv(config.APP_CONFIG, filepath.Join("..", "configs", "config.app.yml")) t.Setenv(config.APP_CONFIG_SECRETS, filepath.Join("..", "configs", "config.secrets.yml")) @@ -135,3 +142,18 @@ func Test_WidgetsConfig(t *testing.T) { require.Equal(t, "p2", w.Credentials.Password) require.Equal(t, "v1", w.Nested.Nested2.Nested3.Value) } + +func Test_ReadRegexp(t *testing.T) { + t.Setenv(config.APP_CONFIG, filepath.Join("testdata", "with-regexp.yml")) + t.Setenv(config.APP_CONFIG_SECRETS, "") + + cfg := &GlobalConfigModel{} + + service := config.NewService(log.NewDefaultLogger()) + err := service.LoadFromFS(cfg, base.ConfigDefaults) + require.Nil(t, err) + + patterns := cfg.Config.Search.Patterns + require.Len(t, patterns, 1) + require.Equal(t, "a(b+)c", patterns[0].String()) +} diff --git a/config/testdata/with-regexp.yml b/config/testdata/with-regexp.yml new file mode 100644 index 00000000..b8fc526f --- /dev/null +++ b/config/testdata/with-regexp.yml @@ -0,0 +1,4 @@ +Config: + Search: + Patterns: + - "a(b+)c"