我有时间学习 Go,但在处理 yaml 文件时遇到了问题。
这是我的 yaml 文件
---
endpoints:
service1:
url: "https://service1.com"
frequency: 2
interval: 1
service2:
url: "https://service2.com"
frequency: 3
interval: 2
我的代码package main
import (
"fmt"
"io/ioutil"
"reflect"
"gopkg.in/yaml.v3"
)
// Config define estrutura do arquivo de configuração
type Config struct {
Endpoint map[string]interface{} `yaml:"endpoints"`
}
func main() {
yamlFile, err := ioutil.ReadFile("config.yml")
if err != nil {
fmt.Printf("Error reading YAML file: %s\n", err)
return
}
var yamlConfig Config
err = yaml.Unmarshal(yamlFile, &yamlConfig)
if err != nil {
fmt.Printf("Error parsing YAML file: %s\n", err)
}
for k := range yamlConfig.Endpoint {
nm := reflect.ValueOf(yamlConfig.Endpoint[k])
for _, key := range nm.MapKeys() {
strct := nm.MapIndex(key)
fmt.Println(key.Interface(), strct.Interface())
}
}
}
// PingEndpoint acessa os endpoint informados
func PingEndpoint(url string, frequency, interval int) {
// do something
}
有没有更好的方法来定义配置结构而不使用接口(interface)?并且真的有必要使用反射来获取 service1
的属性还是存在更好的乳清来做到这一点?
最佳答案
一般来说,interface{}
如果您不知道结构,则在这种情况下使用。在这种情况下,结构似乎是固定的:
type Service struct {
URL string `yaml:"url"`
Frequency int `yaml:"frequency"`
Interval int `yaml:"interval"`
}
type Config struct {
Endpoint map[string]Service `yaml:"endpoints"`
}
对于您的第二个问题,您不再需要在执行此操作后处理未知字段,但即使您有接口(interface){},您也可以使用类型断言(类型 yaml 库将 yaml 解码为 map[interface{}]interface{} ):for k := range yamlConfig.Endpoint {
if mp, ok:=yamlConfig.Endpoint[k].(map[interface{}]interface{}); ok {
for key, value:=range mp {
}
}
}
关于go - 从文件中的 yaml 对象获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63856432/