Go解析Yaml檔案
阿新 • • 發佈:2021-06-25
Yaml 檔案內容(test.yaml)
cache:
enable : false
list : [redis,mongoDB]
mysql:
user : root
password : wangJiLe
host : 11.22.33.44
port : 3306
name : world
Go解析test.yaml檔案(gopkg.in/yaml.v2包)
- Goalng版本1.16.5
go mod init demo
go get gopkg.in/yaml.v2
解析程式碼如下
package main import ( "fmt" "io/ioutil" yaml "gopkg.in/yaml.v2" ) type Yaml struct { Cache struct { Enable bool `yaml:"enable"` List []string `yaml:"list"` } MySQL struct { User string `yaml:"user"` Password string `yaml:"password"` Host string `yaml:"host"` Port string `yaml:"port"` Name string `yaml:"name"` } } func main() { var conf Yaml yamlFile, err := ioutil.ReadFile("test.yaml") if err != nil { fmt.Println(err) return } if err = yaml.Unmarshal(yamlFile, &conf); err != nil { fmt.Println(err) return } fmt.Println(conf.MySQL.Host) fmt.Println(conf.MySQL.Name) fmt.Println(conf.MySQL.Password) fmt.Println(conf.MySQL.Port) fmt.Println(conf.MySQL.User) fmt.Println(conf.Cache.Enable) for _, v := range conf.Cache.List { fmt.Println("Cache:", v) } }
編譯,執行
go build
./demo
11.22.33.44
world
wangJiLe
3306
root
false
Cache: redis
Cache: mongoDB