Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.3k views
in Technique[技术] by (71.8m points)

go - Reading a slice of maps with Golang Viper

I'm using the excellent viper library from here: https://github.com/spf13/viper

I'm trying to read in a config file in hcl (although it could be a JSOn or YAML file as well) which looks like this:

interval = 10
statsd_prefix = "pinger"



group "dns" {
  target_prefix = "ping"
  target "dns" {
    hosts = [
      "dnsserver1",
      "dnsserver2"
    ]
  }
}

The code I have so far looks like this:

viper.SetConfigName("config")
viper.AddConfigPath(".")

err := viper.ReadInConfig()

if err != nil {
  panic(fmt.Errorf("Fatal error config file: %s 
", err))
}

interval := viper.GetInt("interval")
prefix := viper.GetString("statsd_prefix")

groups := viper.GetStringMap("group")

fmt.Println(interval)
fmt.Println(prefix)

The big problem I'm having is with the group option. This can be multiple different groups.

It doesn't seem to work when I read it in using viper.GetStringMap, so I used the standard viper.Get function. The resulting structure looks like this when dumped:

([]map[string]interface {}) (len=1 cap=1) {
 (map[string]interface {}) (len=1) {
  (string) (len=3) "dns": ([]map[string]interface {}) (len=1 cap=2) {
   (map[string]interface {}) (len=2) {
    (string) (len=13) "target_prefix": (string) (len=4) "ping",
    (string) (len=6) "target": ([]map[string]interface {}) (len=1 cap=1) {
     (map[string]interface {}) (len=1) {
      (string) (len=8) "dns": ([]map[string]interface {}) (len=1 cap=1) {
       (map[string]interface {}) (len=1) {
        (string) (len=5) "hosts": ([]interface {}) (len=2 cap=2) {
         (string) (len=18) "dnsserver1",
         (string) (len=18) "dnsserver2"
        }
       }
      }
     }
    }
   }
  }
 }
}

It seems to be of type slice when I use reflect. Do I need to cast it to a slice? How do I do that? Is there an easier way of managing a data structure like this?

I'm completely new to golang, so please go easy on me :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...