How to read a YAML file

后端 未结 2 1430
长发绾君心
长发绾君心 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:45

    An example conf.yaml file:

    conf:
      hits: 5
      time: 5000000
      camelCase: Just a name :)
    

    The main.go file:

    package main
    
    import (
        "fmt"
        "io/ioutil"
        "log"
    
        "gopkg.in/yaml.v2"
    )
    
    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)
    }
    

    Running instructions (in case it's the first time you step out of stdlib):

    go mod init example.com/whatever
    go get gopkg.in/yaml.v2
    cat go.sum
    go run .
    

    The tags (yaml:"conf" etc.) are optional for any all-lowercase yaml key identifiers. I've included one for a camelCase identifier.

提交回复
热议问题