golang解析yaml遇到的坑

  • golang 文件
package main

import (
    "fmt"
    "io/ioutil"
    "log"

    yaml "gopkg.in/yaml.v2"
)

//Yaml the yaml file Cluster struct
type Yaml struct {
    Testclu struct {  //Testclu对应yaml文件里的testclu,yaml文件里的字母要小写,对大小写敏感
        Hostips     []string `yaml:"hostips,flow"` //Hostips是个数组,后面yaml:"要跟yaml文件里的hostips",否则找不到字段
        Port        string   `yaml:"port"`
        DBuser      string   `yaml:"dbuser"`
        Passwd      string   `yaml:"passwd"`
        ServiceName string   `yaml:"service_name"`
    }
}

func main() {
    cluster := new(Yaml)
    yamlFile, err := ioutil.ReadFile("cluster.yaml")
    if err != nil {
        log.Println(err)
    }

    err = yaml.Unmarshal(yamlFile, &cluster)

    if err != nil {
        log.Println(err)
    }

    log.Println("conf", cluster)
    fmt.Println(cluster.Testclu.Hostips)

}
  • Yaml文件
testclu:
  hostips: 
    - 192.168.3.1
    - 192.168.3.2
    - 192.168.3.3
  port: 1521
  dbuser: system
  passwd: 123456
  service_name: testdb

你可能感兴趣的:(golang解析yaml遇到的坑)