gpt4 book ai didi

go - 使用 Viper 语言处理界面

转载 作者:IT王子 更新时间:2023-10-29 00:43:34 24 4
gpt4 key购买 nike

我正在使用 Viper 构建一个小应用程序和 Cobra .目前,我有一个像这样的 yaml 文件:

hosts:
- name: host1
port: 90
key: my_key
- name: host2
port: 90
key: prompt

而且我已经使用 Viper 读取了配置文件。

当我运行 viper.Get("hosts") 时,它返回一个接口(interface)(或接口(interface)的一部分?)。这是我最终得到的数据结构:

([]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
}
}

我想在这里做的是遍历每个数组元素并使用名称、端口和 key 的值执行操作。

我对 Golang 中的接口(interface)完全陌生,所以这不是很清楚,而且这方面的文献非常困惑:(

感谢任何帮助。

最佳答案

通过定义配置文件类型并使用 viper.Unmarshal,您可以将接口(interface)转换为您需要的特定类型。这是一个例子:

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)
}
}

test.yml

hosts:
- name: host1
port: 90
key: my_key
- name: host2
port: 90
key: prompt

运行:

$ go run main.go
Name: host1, Port: 90, Key: my_key
Name: host2, Port: 90, Key: prompt

如果你只想解码一些 key ,而不是整个配置文件,请使用 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)
}
}

运行:

$ go run main.go
Name: host1, Port: 90, Key: my_key
Name: host2, Port: 90, Key: prompt

关于go - 使用 Viper 语言处理界面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42747085/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com