如何使用Go Viper包解析配置条目的标题?

huangapple go评论70阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2022年10月7日 22:39:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/73988842.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定