Reading Slices of Maps with Golang Viper
The Viper library is an excellent tool for reading and managing configuration data in Go. One common challenge users face is reading a slice of maps from a configuration file.
Consider the following HCL configuration file:
interval = 10 statsd_prefix = "pinger" group "dns" { target_prefix = "ping" target "dns" { hosts = [ "dnsserver1", "dnsserver2" ] } }
To read this configuration file with Viper, you can use the following code:
type config struct { Interval int `mapstructure:"interval"` StatsdPrefix string `mapstructure:"statsd_prefix"` Groups []group `mapstructure:"group"` } type group struct { Name string `mapstructure:"group"` TargetPrefix string `mapstructure:"target_prefix"` Targets []target `mapstructure:"target"` } type target struct { Name string `mapstructure:"target"` Hosts []string `mapstructure:"hosts"` } func main() { viper.SetConfigName("config") viper.AddConfigPath(".") err := viper.ReadInConfig() if err != nil { panic(err) } var c config err = viper.Unmarshal(&c) if err != nil { panic(err) } fmt.Println(c.Interval) fmt.Println(c.StatsdPrefix) fmt.Println("Groups:") for _, group := range c.Groups { fmt.Println("- Name:", group.Name) fmt.Println(" - Prefix:", group.TargetPrefix) fmt.Println(" - Targets:") for _, target := range group.Targets { fmt.Println(" - Name:", target.Name) fmt.Println(" - Hosts:") for _, host := range target.Hosts { fmt.Println(" - ", host) } } } }
By defining Go structures to match the configuration file, Viper can automatically decode and map the configuration data to the correct types. This simplifies working with complex data structures and provides a type-safe way to access configuration values.
The above is the detailed content of How to Read Slices of Maps from Configuration Files Using Golang Viper?. For more information, please follow other related articles on the PHP Chinese website!