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

Maps configuration with value including colon character #180

Open
T-PWK opened this issue Sep 3, 2020 · 3 comments
Open

Maps configuration with value including colon character #180

T-PWK opened this issue Sep 3, 2020 · 3 comments

Comments

@T-PWK
Copy link

T-PWK commented Sep 3, 2020

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?

@sepehrhakimi90
Copy link

sepehrhakimi90 commented Sep 9, 2020

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
}

@bsdlp
Copy link

bsdlp commented Oct 22, 2020

this pr addresses #184

@prusnak
Copy link

prusnak commented Jul 12, 2022

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants