【问题标题】:Getting value from yaml object in file从文件中的 yaml 对象获取值
【发布时间】:2020-09-12 03:05:22
【问题描述】:

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

}

有没有更好的方法来定义配置结构而不使用接口?真的有必要使用反射来获取service1 的属性或存在更好的乳清吗?

【问题讨论】:

    标签: go yaml


    【解决方案1】:

    通常,如果您不知道结构,则在这种情况下使用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{},您也可以使用类型断言(type yaml library unmarshals yaml into a map[interface{}]接口{}):

    for k := range yamlConfig.Endpoint {
         if mp, ok:=yamlConfig.Endpoint[k].(map[interface{}]interface{}); ok {
             for key, value:=range mp {
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-16
      • 1970-01-01
      • 2023-03-03
      • 2019-01-24
      • 1970-01-01
      • 2021-02-25
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多