envconfig
envconfig copied to clipboard
Maps configuration with value including colon character
Hi
The envconfig library is amazing. However, I've run into an issue where I cannot configure map of strings (map[string]string
) where value contains colon character.
Basically I am trying to keep a map of URLs like dev:https://foo.com,prod:https://bar.com
.
Configuration structure is as follows:
type Config struct {
Schedule string
Port int
User string
Passwd string
Urls map[string]string
}
After calling envconfig.Process
the Urls
property is empty. If I remove ':' from values, it works perfectly fine.
Is there any workaround to that problem?
Hi This solution would be helpful in this situation till the issue resolve generally in map parsing. in this solution we define MyMap type and implement Setter interface. This would be helpful till add ignoring char to this module. Your URLs must be set in this format: dev:https\://foo.com,prod:https\://bar.com
Code:
type MyMap map[string]string
type Config struct {
Schedule string
Port int
User string
Passwd string
Urls map[string]string
}
func (m *MyMap) Set(value string) error{
list := MyMap{}
regexSpliter := `[^\\]:`
reg, err := regexp.Compile(regexSpliter)
if err != nil {
return err
}
if len(strings.TrimSpace(value)) != 0 {
pairs := strings.Split(value, ",")
for _, pair := range pairs {
sepRange := reg.FindAllStringIndex(pair, -1)
if len(sepRange) != 1 {
return fmt.Errorf("invalid map item: %q", pair)
}
key := pair[0:sepRange[0][0]+1]
val := strings.Replace(pair[sepRange[0][1]:], "\\:", ":", -1)
list[key]=val
}
}
*m = MyMap(list)
return nil
}
this pr addresses https://github.com/kelseyhightower/envconfig/pull/184
go-envconfig can override separator via separator
keyword: https://github.com/sethvargo/go-envconfig#separator