英文:
How to unmarshall config entry header with Go Viper package?
问题
我有一个配置文件,内容如下:
apps:
customer1:
upload_path: "/opt/uploads/customer1"
local_path: "/opt/ready/customer1"
bucket: "b1"
customer2:
upload_path: /opt/uploads/customer2
local_path: opt/ready/customer2,
bucket: "b2"
我正在使用 Viper 加载和读取配置文件。
我正在将上述配置文件解组并映射到以下结构体:
type AppConfig struct {
UploadPath string `mapstructure:"upload_path"`
LocalPath string `mapstructure:"local_path"`
Bucket string `mapstructure:"bucket"`
}
appconfigs []*AppConfig
viper.SetConfigName(configName)
viper.SetConfigType("yaml")
viper.AddConfigPath(".")
viper.UnmarshalKey("apps", &appconfigs)
我试图解决的问题是如何在不在配置文件中添加冗余字段的情况下获取条目的标题(即 customer1 和 customer2),以避免以下情况:
apps:
customer1:
name: customer1
upload_path: "/opt/uploads/customer1"
local_path: "/opt/ready/customer1"
bucket: "b1"
请注意,我只提供翻译服务,不会回答关于翻译内容的问题。
英文:
I have a configuration file that looks like the following:
apps:
customer1:
upload_path: "/opt/uploads/customer1"
local_path: "/opt/ready/customer1"
bucket: "b1"
customer2:
upload_path: /opt/uploads/customer2
local_path: opt/ready/customer2,
bucket: "b2"
I am using Viper to load and read the configuration file.
I am unmarshalling the above config and mapping it to the following struct:
type AppConfig struct {
UploadPath string `mapstructure:"upload_path"`
LocalPath string `mapstructure:"local_path"`
Bucket string `mapstructure:"bucket"`
}
appconfigs []*AppConfig
viper.SetConfigName(configName)
viper.SetConfigType("yaml")
viper.AddConfigPath(".")
viper.UnmarshalKey("apps", &appconfigs)
The problem I am trying to solve is getting the entry header (ie customer1 and customer2) without having to have a redundant field in my config file and ending up with:
apps:
customer1:
name: customer1
upload_path: "/opt/uploads/customer1"
local_path: "/opt/ready/customer1"
bucket: "b1"
答案1
得分: 1
配置可以解组为一个映射:
var appconfigs map[string]*AppConfig
viper.UnmarshalKey("apps", &appconfigs)
你可以从映射键中获取名称。
英文:
The configuration can be unmarshaled to a map:
var appconfigs map[string]*AppConfig
viper.UnmarshalKey("apps", &appconfigs)
You can get the names from the map key.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论