登录
首页 >  Golang >  Go问答

使用Go语言遍历YAML文件

来源:stackoverflow

时间:2024-03-15 10:57:28 239浏览 收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《使用Go语言遍历YAML文件》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

问题内容

我想知道这个逻辑在 golang 中是否可行。我有一个这样的 yaml 文件:

initsteps:
  - "pip install --upgrade pip"
  - "python3 --version"

buildsteps:
  - "pip install ."

runprocess:
  - "python3 test.py"

并且我使用 gopkg.in/yaml.v3 来迭代这些步骤。我下面有一个函数,可以将说明放入地图中,如下所示:

func init() {

    // add map from yaml to steps
    f, err := ioutil.readfile(devrun)

    if err != nil {
        panic(err)
    }
    steps = make(map[interface{}]interface{})

    err2 := yaml.unmarshal(f, &steps)

    if err2 != nil {
        panic(err2)
    }
}

在我的 main 函数中,如果键匹配,则可以迭代这些值:

for k, v := range steps {
        if k == "initSteps" {
            s := reflect.ValueOf(v)
            for i := 0; i < s.Len(); i++ {
                singleVertex := s.Index(i).Elem()
                fmt.Println(singleVertex)
            }
        }
    }

我想看看是否可以迭代 steps 中的密钥,以及如何添加它。这样我就可以如果 k.initsteps: yaml 文件中的密钥将始终与唯一改变的是它们下面的步骤。


正确答案


您可以使用 viper 读取 .yaml 配置文件。简单代码示例:

import (
    "fmt"
    "github.com/spf13/viper"
)

func main() {
    readyaml()
}

func readyaml() {
    viper.setconfigname("test")                // name of config file (without extension)
    viper.setconfigtype("yaml")                // required if the config file does not have the extension in the name
    viper.addconfigpath("./examples/readyaml") // path to look for the config file in

    err := viper.readinconfig() // find and read the config file
    if err != nil {             // handle errors reading the config file
        panic(fmt.errorf("fatal error config file: %w", err))
    }
    fmt.println(viper.allkeys())
    for _, i := range viper.allkeys() {
        fmt.println(i, viper.get(i))
    }

}

输出:

[initsteps buildsteps runprocess]

initsteps [pip install --upgrade pip python3 --version]

buildsteps [pip install .]

runprocess [python3 test.py]

今天关于《使用Go语言遍历YAML文件》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>