Home > Net >  GoLang iterate over yaml file
GoLang iterate over yaml file

Time:06-29

I wanted to know if this logic is possible in Golang. I have a yaml file as such:

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

buildSteps:
  - "pip install ."

runProcess:
  - "python3 test.py"

And am using gopkg.in/yaml.v3 to iterate over the steps. I have a function below that puts the instructions into a map like this:


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)
    }
}

And in my main function have this to iterate over the values if the key matches:

    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)
            }
        }
    }

I wanted to see if it was possible to iterate over the key from steps though and how I would go about adding this in. This way I can if k.initSteps: The keys from the yaml file will always be the same with the only thing changing being the steps under them.

CodePudding user response:

You can read your .yaml config file with viper. Simple code example:

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))
    }

}

Output:

[initsteps buildsteps runprocess]

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

buildsteps [pip install .]

runprocess [python3 test.py]
  •  Tags:  
  • go
  • Related