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: custom key value separator #284

Merged
merged 3 commits into from
Sep 29, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
9 changes: 7 additions & 2 deletions env.go
Original file line number Diff line number Diff line change
Expand Up @@ -518,11 +518,16 @@ func handleMap(field reflect.Value, value string, sf reflect.StructField, funcMa
separator = ","
}

keyValSeparator := sf.Tag.Get("envKeyValSeparator")
if keyValSeparator == "" {
keyValSeparator = ":"
}

result := reflect.MakeMap(sf.Type)
for _, part := range strings.Split(value, separator) {
pairs := strings.Split(part, ":")
pairs := strings.Split(part, keyValSeparator)
if len(pairs) != 2 {
return newParseError(sf, fmt.Errorf(`%q should be in "key:value" format`, part))
return newParseError(sf, fmt.Errorf(`%q should be in "key%svalue" format`, part, keyValSeparator))
}

key, err := keyParserFunc(pairs[0])
Expand Down
4 changes: 2 additions & 2 deletions env_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -403,7 +403,7 @@ func TestParsesEnv(t *testing.T) {

func TestParsesEnv_Map(t *testing.T) {
type config struct {
MapStringString map[string]string `env:"MAP_STRING_STRING" envSeparator:","`
MapStringString map[string]string `env:"MAP_STRING_STRING" envSeparator:"," envKeyValSeparator:"|"`
caarlos0 marked this conversation as resolved.
Show resolved Hide resolved
MapStringInt64 map[string]int64 `env:"MAP_STRING_INT64"`
MapStringBool map[string]bool `env:"MAP_STRING_BOOL" envSeparator:";"`
}
Expand All @@ -412,7 +412,7 @@ func TestParsesEnv_Map(t *testing.T) {
"k1": "v1",
"k2": "v2",
}
t.Setenv("MAP_STRING_STRING", "k1:v1,k2:v2")
t.Setenv("MAP_STRING_STRING", "k1|v1,k2|v2")

msi := map[string]int64{
"k1": 1,
Expand Down