Home > Backend Development > Golang > How to Read Slices of Maps from Configuration Files Using Golang Viper?

How to Read Slices of Maps from Configuration Files Using Golang Viper?

DDD
Release: 2024-11-26 04:46:22
Original
689 people have browsed it

How to Read Slices of Maps from Configuration Files Using Golang Viper?

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"
    ]
  }
}
Copy after login

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)
            }
        }
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template