I have a dotenv file in the current format
KEY_PATH=/keys
LOG_LEVEL=WARNING
DB_CUSTOMER1=dbone
DB_CUSTOMER2=dbtwo
I also have a struct in the form of
type MyConfiguration struct {
KeyPath string `mapstructure:"KEY_PATH"`
CustomerDB map[string]string `<???>`
LogLevel string `mapstructure:"LOG_LEVEL"`
}
I'm looking and failing to find a way where I could map config keys taken as DB_CUSTOMER1=val
to a map in the form of "CUSTOMER1": "val"
either manually (eg: ask Viper for all keys with prefix DB_ and then set them myself) or automatically (but it seems Viper doesn't have a way to extract key/values this way).
I would appreciate any pointers.
Thanks!
spf13/viper predominantly uses mapstructure package to convert between one native Go type to another i.e. when un-marshaling. You need to define an annotation that would cause any unused values to this map. There is an option to collect such reminder values. You need to modify the map to take an interface as
which would collect all your
DB_*
field values to the map as interface types, which you can type assert to get the required string value.