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.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

kmuchmore opened this issue · comments

commented

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

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:

  • Use the env provider to read the env var VAR.
  • Write a custom function that then gets VAR's value, splits it to key-value pairs and populates the map.

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

  • ENV_KEY1
  • ENV_KEY2