kelseyhightower / envconfig

Golang library for managing configuration data from environment variables
MIT License
5.01k stars 377 forks source link

Maps configuration with value including colon character #180

Open T-PWK opened 4 years ago

T-PWK commented 4 years ago

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 commented 4 years ago

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 commented 3 years ago

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

prusnak commented 2 years ago

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