如何读取YAML文件 [英] How to read a YAML file

查看:44
本文介绍了如何读取YAML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在读取YAML文件时遇到问题.我认为这是文件结构中的某物,但我不知道是什么.

I have an issue with reading a YAML file. I think it's something in the file structure but I can't figure out what.

YAML文件:

conf:
  hits:5
  time:5000000

代码:

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
}

推荐答案

您的Yaml文件必须为

your yaml file must be

hits: 5
time: 5000000

您的代码应如下所示:

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

主要错误是您的结构的大写字母.

the main error was capital letter for your struct.

这篇关于如何读取YAML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆