Home > Mobile >  Parse nested map from a YAML document
Parse nested map from a YAML document

Time:12-18

I am having trouble with (what I believe to be) a simple issue. I am trying to create a CLI using commando, and this CLI will read a configuration yaml, and then do stuff. However, I am stuck at the parsing of the config.yaml The following is my code:

type Config struct {
    Apps map[string]App `yaml:"apps"`
    Branch string  `yaml:"branch"`
}
type App struct {
    hostName string `yaml:"hostName"`
}
.
. //func main, and other standard stuff goes here
.
commando.
        Register("read").
        AddArgument("config", "read yaml file", "./config.yaml").
        SetAction(
            func(args map[string]commando.ArgValue, flags map[string]commando.FlagValue) {
                    //args["config"] equates to ./config.yaml and I will give that below
                    file, err := ioutil.ReadFile(args["config"].Value)
                    if err != nil {
                        log.Fatal(err)
                    }

                    var data2 Config
                    err3 := yaml.Unmarshal(file, &data2)
                    if err3 != nil {
                        log.Fatal(err3)
                    }
                    fmt.Printf("Ad demo?: %#v\n", data2.Apps["ad-demo"].hostName)
                    fmt.Printf("Data 2: %#v\n", data2)
            })
        commando.Parse(nil)

My config.yaml is as follows:

apps:
  ad-tag:
    hostName: ad-tag1.krg.io
  ad-demo:
    hostName: demo1.krg.io
branch: KAT-3821

This works for the most part. The problem is that the following prints:

Ad demo?: ""
Data 2: main.Config{Apps:map[string]main.App{"ad-demo":main.App{hostName:""}, "ad-tag":main.App{hostName:""}}, Branch:"KAT-3821"}

The hostName is coming up as an empty string.

Any idea as to what I am doing wrong? I feel like this should be very simple, but I cannot for the life of me figure out what I am doing wrong.

Thanks

CodePudding user response:

Hostname should be exported, i.e. capitalized

type App struct {
    HostName string `yaml:"hostName"`
}

If you don't export it, packages such as yaml or json won't be able to read the field and populate it.

  • Related