我在阅读YAML文件时遇到问题.我认为它是文件结构中的东西,但我无法弄清楚是什么.
YAML文件:
conf:
hits:5
time:5000000
Run Code Online (Sandbox Code Playgroud)
码:
type conf struct {
hits int64 `yaml:"hits"`
time int64 `yaml:"time"`
}
func (c *conf) getConf() *conf {
yamlFile, err := ioutil.ReadFile("conf.yaml")
if err != nil {
log.Printf("yamlFile.Get err #%v ", err)
}
err = yaml.Unmarshal(yamlFile, c)
if err != nil {
log.Fatalf("Unmarshal: %v", err)
}
return c
}
Run Code Online (Sandbox Code Playgroud)
qwe*_*max 47
你的yaml文件必须是
hits: 5
time: 5000000
Run Code Online (Sandbox Code Playgroud)
您的代码应如下所示:
package main
import (
"fmt"
"gopkg.in/yaml.v2"
"io/ioutil"
"log"
)
type conf struct {
Hits int64 `yaml:"hits"`
Time int64 `yaml:"time"`
}
func (c *conf) getConf() *conf {
yamlFile, err := ioutil.ReadFile("conf.yaml")
if err != nil {
log.Printf("yamlFile.Get err #%v ", err)
}
err = yaml.Unmarshal(yamlFile, c)
if err != nil {
log.Fatalf("Unmarshal: %v", err)
}
return c
}
func main() {
var c conf
c.getConf()
fmt.Println(c)
}
Run Code Online (Sandbox Code Playgroud)
主要错误是结构的大写字母.
使用升级版本 3的 yaml 包。
一个示例conf.yaml文件:
conf:
hits: 5
time: 5000000
camelCase: sometext
Run Code Online (Sandbox Code Playgroud)
该main.go文件:
package main
import (
"fmt"
"io/ioutil"
"log"
"gopkg.in/yaml.v3"
)
type myData struct {
Conf struct {
Hits int64
Time int64
CamelCase string `yaml:"camelCase"`
}
}
func readConf(filename string) (*myData, error) {
buf, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
c := &myData{}
err = yaml.Unmarshal(buf, c)
if err != nil {
return nil, fmt.Errorf("in file %q: %v", filename, err)
}
return c, nil
}
func main() {
c, err := readConf("conf.yaml")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%v", c)
}
Run Code Online (Sandbox Code Playgroud)
运行说明(以防这是您第一次退出 stdlib):
go mod init example.com/whatever
go get gopkg.in/yaml.v3
cat go.sum
go run .
Run Code Online (Sandbox Code Playgroud)
标签(如yaml:"field")对于任何全小写的 yaml 密钥标识符都是可选的。对于节目,我已经包含了一个用于驼峰式标识符的节目。
(令人困惑的是,“YAML”的这个小写字母行为没有看到标准的“JSON”包。如果你的结构有两种JSON和YAML编码最好是在字面上各个领域。放牧,同时指定标签中使用,但减少了错误。 )
| 归档时间: |
|
| 查看次数: |
38623 次 |
| 最近记录: |