我正在使用Viper和Cobra构建一个小应用程序。目前,我有一个yaml文件,如下所示:
hosts:
- name: host1
port: 90
key: my_key
- name: host2
port: 90
key: prompt
Run Code Online (Sandbox Code Playgroud)
而且我已经使用Viper读取了配置文件。
当我运行viper.Get("hosts")
它时,它返回一个接口(或接口的一部分?)。这是我最终得到的数据结构:
([]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
}
}
Run Code Online (Sandbox Code Playgroud)
我想在这里做的是遍历每个数组元素,并使用name,port和key的值执行操作。
我是Golang接口的新手,所以这还不是很清楚,关于此的文献非常令人困惑:(
任何帮助表示赞赏。
通过定义配置文件类型并使用viper.Unmarshal
,可以将接口转换为所需的特定类型。这是一个例子:
main.go
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\n", h.Name, h.Port, h.Key)
}
}
Run Code Online (Sandbox Code Playgroud)
test.yml
hosts:
- name: host1
port: 90
key: my_key
- name: host2
port: 90
key: prompt
Run Code Online (Sandbox Code Playgroud)
跑:
$ go run main.go
Name: host1, Port: 90, Key: my_key
Name: host2, Port: 90, Key: prompt
Run Code Online (Sandbox Code Playgroud)
如果您只想解码一些密钥,而不是整个配置文件,请使用viper.UnmarshalKey
。
main.go
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\n", h.Name, h.Port, h.Key)
}
}
Run Code Online (Sandbox Code Playgroud)
跑:
$ go run main.go
Name: host1, Port: 90, Key: my_key
Name: host2, Port: 90, Key: prompt
Run Code Online (Sandbox Code Playgroud)