Working with interfaces using Viper language
我正在使用Viper和Cobra构建一个小应用程序。 目前,我有一个yaml文件,如下所示:
1 2 3 4 5 6 7 | hosts: - name: host1 port: 90 key: my_key - name: host2 port: 90 key: prompt |
而且我已经使用Viper读取了配置文件。
当我运行
1 2 3 4 5 6 7 8 9 10 11 12 | ([]interface {}) (len=2 cap=2) { (map[interface {}]interface {}) (len=3) { (string) (len=4)"name": (string) (len=20)"host1", (string) (len=4)"port": (int) 90, (string) (len=3)"key": (string) (len=6)"my_key" }, (map[interface {}]interface {}) (len=3) { (string) (len=3)"key": (string) (len=6)"prompt", (string) (len=4)"name": (string) (len=20)"host2", (string) (len=4)"port": (int) 90 } } |
我想在这里做的是遍历每个数组元素,并使用name,port和key的值执行操作。
我对Golang中的接口完全陌生,所以这还不是很清楚,关于此的文献非常令人困惑:(
任何帮助表示赞赏。
通过定义配置文件类型并使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | package main import ( "fmt" "github.com/spf13/viper" ) type Host struct { Name string Port int Key string } type Config struct { Hosts []Host } func main() { viper.AddConfigPath("./") viper.SetConfigName("test") viper.ReadInConfig() var config Config err := viper.Unmarshal(&config) if err != nil { panic("Unable to unmarshal config") } for _, h := range config.Hosts { fmt.Printf("Name: %s, Port: %d, Key: %s ", h.Name, h.Port, h.Key) } } |
1 2 3 4 5 6 7 | hosts: - name: host1 port: 90 key: my_key - name: host2 port: 90 key: prompt |
跑:
1 2 3 | $ go run main.go Name: host1, Port: 90, Key: my_key Name: host2, Port: 90, Key: prompt |
如果您只想解码一些密钥,而不是整个配置文件,请使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | package main import ( "fmt" "github.com/spf13/viper" ) type Host struct { Name string Port int Key string } func main() { viper.AddConfigPath("./") viper.SetConfigName("test") viper.ReadInConfig() var hosts []Host err := viper.UnmarshalKey("hosts", &hosts) if err != nil { panic("Unable to unmarshal hosts") } for _, h := range hosts { fmt.Printf("Name: %s, Port: %d, Key: %s ", h.Name, h.Port, h.Key) } } |
跑:
1 2 3 | $ go run main.go Name: host1, Port: 90, Key: my_key Name: host2, Port: 90, Key: prompt |