GoLang 遍历 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 文件的密钥将始终相同,唯一改变的是步骤在他们之下。


开心每一天1111
浏览 122回答 1
1回答

慕沐林林

您可以使用 viper 读取您的 .yaml 配置文件。简单代码示例:import (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "github.com/spf13/viper")func main() {&nbsp; &nbsp; readYaml()}func readYaml() {&nbsp; &nbsp; viper.SetConfigName("test")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // name of config file (without extension)&nbsp; &nbsp; viper.SetConfigType("yaml")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // REQUIRED if the config file does not have the extension in the name&nbsp; &nbsp; viper.AddConfigPath("./Examples/readyaml") // path to look for the config file in&nbsp; &nbsp; err := viper.ReadInConfig() // Find and read the config file&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Handle errors reading the config file&nbsp; &nbsp; &nbsp; &nbsp; panic(fmt.Errorf("fatal error config file: %w", err))&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(viper.AllKeys())&nbsp; &nbsp; for _, i := range viper.AllKeys() {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(i, viper.Get(i))&nbsp; &nbsp; }}输出:[initsteps buildsteps runprocess]initsteps [pip install --upgrade pip python3 --version]buildsteps [pip install .]runprocess [python3 test.py]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go