Go Unmarshaling YAML into struct

huangapple go评论80阅读模式
英文:

Go Unmarshaling YAML into struct

问题

我正在尝试将一个YAML数据解析为字符串:

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

由于某种原因,config是一个空结构体&{}

英文:

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.

答案1

得分: 8

你的结构体字段是未导出的。请将它们导出,然后它们就可以正常工作了。

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

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

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

答案2

得分: 2

首字母大写很重要:

foo_bar --> Foo_bar

英文:

The capital matters:

foo_bar --> Foo_bar

huangapple
  • 本文由 发表于 2015年4月10日 00:35:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/29544146.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定