将YAML解组为struct

将YAML解组为struct

问题描述:

I am trying to parse a YAML data into a string:

package main

import (
    "fmt"
    "log"
    "gopkg.in/yaml.v2"
)

type Config struct {
    foo_bar string
}

func FailOnError(err error, msg string) {
    if err != nil {
        log.Fatalf("%s: %s", msg, err)
        panic(fmt.Sprintf("%s: %s", msg, err))
    }
}

func ParseYAMLConfig(data []byte) *Config {
    config := Config{}

    err := yaml.Unmarshal(data, &config)
    if err != nil {
        FailOnError(err, "Failed to unmarshal the config")
    }

    return &config
}

var configYAMLData = `
---
foo_bar: "https://foo.bar"
`

func main() {
    config := ParseYAMLConfig([]byte(configYAMLData))
    fmt.Printf("%v", config)
}

For some reason, config is an empty struct &{} though.

Your struct's fields are unexported. Export them and it'll work.

type Config struct {
    FooBar string `yaml:"foo_bar"`
}

The capital matters:

foo_bar --> Foo_bar