envconfig icon indicating copy to clipboard operation
envconfig copied to clipboard

Maps configuration with value including colon character

Open T-PWK opened this issue 4 years ago • 3 comments

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?

T-PWK avatar Sep 03 '20 14:09 T-PWK

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
}

sepehrhakimi90 avatar Sep 09 '20 15:09 sepehrhakimi90

this pr addresses https://github.com/kelseyhightower/envconfig/pull/184

bsdlp avatar Oct 22 '20 21:10 bsdlp

go-envconfig can override separator via separator keyword: https://github.com/sethvargo/go-envconfig#separator

prusnak avatar Jul 12 '22 09:07 prusnak