Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow config to unmarshal regexes as strings #412

Merged
merged 1 commit into from
Jul 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
"io"
"io/fs"
"os"
"reflect"
"regexp"
"strings"

"github.com/moov-io/base/log"
Expand Down Expand Up @@ -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
}
}
22 changes: 22 additions & 0 deletions config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package config_test

import (
"path/filepath"
"regexp"
"testing"

"github.com/moov-io/base"
Expand All @@ -22,6 +23,8 @@ type ConfigModel struct {
Zero string

Widgets map[string]Widget

Search SearchConfig
}

type Widget struct {
Expand All @@ -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"))
Expand Down Expand Up @@ -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())
}
4 changes: 4 additions & 0 deletions config/testdata/with-regexp.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Config:
Search:
Patterns:
- "a(b+)c"
Loading