go - 从文件中的 yaml 对象获取值

标签 go yaml

我有时间学习 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/

相关文章:

unit-testing - 使用GAE测试时如何获取主机名?

azure - 如何将测试失败屏幕截图附加到 YAML 中的 Azure Pipeline 测试运行?

java - 是否可以使用非 void 的 setter 反序列化 yaml 文档?

go - PHP 相当于 GO 中的 strtotime()

go - 使用 QPid 和 golang 包装器 Electron 连接到 AMQP 1.0 Azure EventHub

rest - 使用 REST API 存储、流式传输视频和处理请求

Python YAML 保留换行符而不添加额外的换行符

security - 如何防止来自用 Go 编写的 HTTP 服务器的 DDoS 攻击?

macos - 错误 : there was a problem with the editor "vi" -- while trying to edit a deployment file in a cluster

json - 有没有像 csv 或 json 这样的东西,但更图形化,更适合人类阅读?