1. 程式人生 > 其它 >Go--解析yaml檔案

Go--解析yaml檔案

yaml 檔案是目前最常用的配置檔案,使用go語言編寫程式碼和工具時,也會用到yaml檔案,將服務配置及中介軟體等資訊定義到yaml檔案中,後續可根據實際場景來選用。

//先下載外部包
go get -u gopkg.in/yaml.v2

1、定義yaml配置檔案

conf/test.yaml

ck:
  host: 11.11.11.11
  port: 9001
  database: db2
  username: test2
  password: 123ck456
user: test
password: 123yy456
host: 10.10.10.10
port: 3306
dbname: db1

2、主程式

package main

import (
    "fmt"
    "gopkg.in/yaml.v3"
    "io/ioutil"
)

type Conn struct {
    Ck struct {
        Host     string `yaml:"host"`
        Port     string `yaml:"port"`
        Database string `yaml:"database"`
        Username string `yaml:"username"`
        Password string
`yaml:"password"` } } type Mysql struct { User string `yaml:"user"` Password string `yaml:"password"` Host string `yaml:"host"` Port string `yaml:"port"` DBname string `yaml:"dbname"` } const cfgFile = "conf/test.yaml" func main() { data, err := ioutil.ReadFile(cfgFile)  //讀取配置檔案的路徑
if err != nil { fmt.Printf("err: %v\n", err) return } var conf Conn if err := yaml.Unmarshal(data, &conf); err != nil {  //將yaml檔案中的資訊反序列化給conf結構體 fmt.Printf("err: %v\n", err) return } yml, _ := yaml.Marshal(conf)  //序列化為yaml檔案 fmt.Printf("conf: %#v\n", conf) fmt.Printf("%s\n", yml) var confs Mysql if err := yaml.Unmarshal(data, &confs); err != nil { fmt.Printf("err: %v\n", err) return } yaml, _ := yaml.Marshal(confs) fmt.Printf("conf: %#v\n", confs) fmt.Printf("%s\n", yaml) }

3、輸出結果

conf: main.Conn{Ck:struct { Host string "yaml:\"host\""; Port string "yaml:\"por
t\""; Database string "yaml:\"database\""; Username string "yaml:\"username\"";
Password string "yaml:\"password\"" }{Host:"11.11.11.11", Port:"9001", Database:
"db2", Username:"test2", Password:"123ck456"}}
ck:
    host: 11.11.11.11
    port: "9001"
    database: db2
    username: test2
    password: 123ck456

conf: main.Mysql{User:"test", Password:"123yy456", Host:"10.10.10.10", Port:"330
6", DBname:"db1"}
user: test
password: 123yy456
host: 10.10.10.10
port: "3306"
dbname: db1
將yaml檔案中的資訊反序列化給Config結構體