Is it possible to map a prefixed list of env values into a map with Viper?

824 views Asked by At

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!

1

There are 1 answers

1
Inian On BEST ANSWER

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

CustomerDB  map[string]interface{} `mapstructure:",remain"`

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.