knadh / koanf

Simple, extremely lightweight, extensible, configuration management library for Go. Support for JSON, TOML, YAML, env, command line, file, S3 etc. Alternative to viper.
MIT License
2.56k stars 146 forks source link

How to populate a map[string]string from environment variables #273

Closed kmuchmore closed 4 months ago

kmuchmore commented 5 months ago

I'm probably missing something, but I'm trying to get my environment variable with key value pairs ENV_VAR="key1=value1,key2=value2" to be placed into a map[string]string struct (or whatever input string format is needed for it to be interpreted as a map). The provider for env vars seems to put everything into a string which then bombs out when unmarshalling. The provider also doesn't have context for what the value will be placed into. I only want to interpret a string as a map[string]string if the type it will be going into is a map[string]string.

type foo struct {
    Val map[string]string  `koanf:"val"`
}

Since there is a koanf tag on the struct that shows it's a map, how would I make it interpret the string in the env var according to the type it will be placed in on the struct.

Thanks

knadh commented 5 months ago

Hi @kmuchmore. Env variables are read as key=value pairs. Your value here is a custom comma separated key-value format in itself which koanf (or any config lib) will recognize. What you can do is:

That said, env variables are typically used like this. The idiomatic approach would be to have: