Home > Software engineering >  How to unmarshall config entry header with Go Viper package?
How to unmarshall config entry header with Go Viper package?

Time:10-08

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"

CodePudding user response:

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.

  • Related