How to read a YAML file

后端 未结 2 1433
长发绾君心
长发绾君心 2021-01-30 21:09

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 file:

conf:
  hits:5         


        
2条回答
  •  半阙折子戏
    2021-01-30 21:41

    your yaml file must be

    hits: 5
    time: 5000000
    

    your code should look like this:

    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.

提交回复
热议问题