Skip to content

Commit

Permalink
fix(config/cors): use strings.Fields for string to string slice fields (
Browse files Browse the repository at this point in the history
  • Loading branch information
GeorgeMac authored Nov 29, 2022
1 parent 0018c5d commit 518ec32
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 3 deletions.
22 changes: 21 additions & 1 deletion internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (

var decodeHooks = mapstructure.ComposeDecodeHookFunc(
mapstructure.StringToTimeDurationHookFunc(),
mapstructure.StringToSliceHookFunc(","),
stringToSliceHookFunc(),
stringToEnumHookFunc(stringToLogEncoding),
stringToEnumHookFunc(stringToCacheBackend),
stringToEnumHookFunc(stringToScheme),
Expand Down Expand Up @@ -188,3 +188,23 @@ func stringToEnumHookFunc[T constraints.Integer](mappings map[string]T) mapstruc
return enum, nil
}
}

// stringToSliceHookFunc returns a DecodeHookFunc that converts
// string to []string by splitting using strings.Fields().
func stringToSliceHookFunc() mapstructure.DecodeHookFunc {
return func(
f reflect.Kind,
t reflect.Kind,
data interface{}) (interface{}, error) {
if f != reflect.String || t != reflect.Slice {
return data, nil
}

raw := data.(string)
if raw == "" {
return []string{}, nil
}

return strings.Fields(raw), nil
}
}
2 changes: 1 addition & 1 deletion internal/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,7 @@ func TestLoad(t *testing.T) {
}
cfg.Cors = CorsConfig{
Enabled: true,
AllowedOrigins: []string{"foo.com", "bar.com"},
AllowedOrigins: []string{"foo.com", "bar.com", "baz.com"},
}
cfg.Cache.Enabled = true
cfg.Cache.Backend = CacheMemory
Expand Down
2 changes: 1 addition & 1 deletion internal/config/testdata/advanced.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ ui:

cors:
enabled: true
allowed_origins: "foo.com,bar.com"
allowed_origins: "foo.com bar.com baz.com"

cache:
enabled: true
Expand Down

0 comments on commit 518ec32

Please sign in to comment.