M
M
Mamol272021-11-10 18:53:42
go
Mamol27, 2021-11-10 18:53:42

How to parse arrays from yaml in golang?

Hello.
I have a yaml file that stores arrays, and I want to read them from there, but nothing comes out, no error, no result. And I can't figure out how to fix it.

spoiler
master: ["10.10.11.8", "10.10.11.9", "10.10.11.0"]
data: ["10.10.11.6", "10.10.11.5", "10.10.11.6"]
kibana: ["10.10.11.10"]
pass: "root"
user: "root"


spoiler
package main

import (
  "fmt"
  "io/ioutil"

  "gopkg.in/yaml.v3"
)

func main() {

  fmt.Println("start")

  c, err := readYaml("./tets.yml")

  if err != nil {
    panic(err.Error())
  }

  fmt.Println(c.data, c.kibana, c.data, c.pass, c.user)

}

type ClusterEnv struct {
  master []string `yaml:"master,flow"`
  data   []string `yaml:"data,flow"`
  kibana []string `yaml:"kibana,flow"`
  user   string   `yaml:"user"`
  pass   string   `yaml:"pass"`
}

func readYaml(filename string) (*ClusterEnv, error) {

  buf, err := ioutil.ReadFile(filename)
  if err != nil {
    return nil, err
  }

  c := &ClusterEnv{}
  err = yaml.Unmarshal(buf, c)
  if err != nil {
    return nil, fmt.Errorf("in file %q: %v", filename, err)
  }

  fmt.Println(c.data, c.kibana, c.data, c.pass, c.user)

  return c, nil
}


start
[] [] []  
[] [] []

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Mamonov, 2021-11-10
@Mamol27

You have fields in the structure that are not exportable, that's why it doesn't work.
Here is a working example

package main

import (
    "fmt"
    "io/ioutil"

    "gopkg.in/yaml.v3"
)

func main() {

    fmt.Println("start")

    c, err := readYaml("./tets.yml")

    if err != nil {
        panic(err.Error())
    }

    fmt.Println(c.Master, c.Kibana, c.Data, c.Pass, c.User)
}

type ClusterEnv struct {
    Master []string `yaml:"master,flow"`
    Data   []string `yaml:"data,flow"`
    Kibana []string `yaml:"kibana,flow"`
    User   string   `yaml:"user"`
    Pass   string   `yaml:"pass"`
}

func readYaml(filename string) (*ClusterEnv, error) {

    buf, err := ioutil.ReadFile(filename)
    if err != nil {
        return nil, err
    }

    c := &ClusterEnv{}
    err = yaml.Unmarshal(buf, c)
    if err != nil {
        return nil, fmt.Errorf("in file %q: %v", filename, err)
    }

    return c, nil
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question