是否可以使用 Viper 将带前缀的环境值列表映射到地图中?

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

我有一个当前格式的 dotenv 文件

KEY_PATH=/keys
LOG_LEVEL=WARNING
DB_CUSTOMER1=dbone
DB_CUSTOMER2=dbtwo

我也有一个

形式的结构
type MyConfiguration struct {
    KeyPath           string            `mapstructure:"KEY_PATH"`
    CustomerDB map[string]string `<???>`
    LogLevel          string            `mapstructure:"LOG_LEVEL"`
}

我正在寻找但未能找到一种方法,我可以手动将作为 DB_CUSTOMER1=val 的配置键映射到 "CUSTOMER1": "val" 形式的映射(例如:向 Viper 询问所有键使用前缀 DB_ 然后自己设置它们)或自动(但似乎 Viper 没有办法以这种方式提取 key/values)。

如有指点,我将不胜感激。

谢谢!

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。需要修改地图取一个接口as

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

这会将您所有的 DB_* 字段值作为接口类型收集到映射中,您可以键入 assert 以获取所需的字符串值。