前言
Yaml是一種簡潔易懂的文件配置語言,比如其巧妙避開各種封閉符號,如:引號、各種括號等,這些符號在嵌套結構中會變得復雜而難以辨認。對于更加具體的介紹,大家可以去自行Google一下。
本文是在基于golang第三方開源庫yaml.v2的基礎上進行操作的,只是簡單介紹了一下怎樣在golang中對yaml文件進行解析。下面是yaml.v2在github上的地址yaml.v2地址以及在godoc.org上的介紹yaml庫簡介。
正文
下面就直接使用代碼來進行簡單的介紹了。
測試文件如下:
test.yaml
cache:
enable : false
list : [redis,mongoDB]
mysql:
user : root
password : Tech2501
host : 10.11.22.33
port : 3306
name : cwi
test1.yaml
enable : false
list : [redis,mongoDB]
user : root
password : Tech2501
host : 10.11.22.33
port : 3306
name : cwi
yaml.go
package module
// Yaml struct of yaml
type Yaml struct {
Mysql struct {
User string `yaml:"user"`
Host string `yaml:"host"`
Password string `yaml:"password"`
Port string `yaml:"port"`
Name string `yaml:"name"`
}
Cache struct {
Enable bool `yaml:"enable"`
List []string `yaml:"list,flow"`
}
}
// Yaml1 struct of yaml
type Yaml1 struct {
SQLConf Mysql `yaml:"mysql"`
CacheConf Cache `yaml:"cache"`
}
// Yaml2 struct of yaml
type Yaml2 struct {
Mysql `yaml:"mysql,inline"`
Cache `yaml:"cache,inline"`
}
// Mysql struct of mysql conf
type Mysql struct {
User string `yaml:"user"`
Host string `yaml:"host"`
Password string `yaml:"password"`
Port string `yaml:"port"`
Name string `yaml:"name"`
}
// Cache struct of cache conf
type Cache struct {
Enable bool `yaml:"enable"`
List []string `yaml:"list,flow"`
}
main.go
package main
import (
"io/ioutil"
"log"
"module"
yaml "gopkg.in/yaml.v2"
)
func main() {
// resultMap := make(map[string]interface{})
conf := new(module.Yaml)
yamlFile, err := ioutil.ReadFile("test.yaml")
// conf := new(module.Yaml1)
// yamlFile, err := ioutil.ReadFile("test.yaml")
// conf := new(module.Yaml2)
// yamlFile, err := ioutil.ReadFile("test1.yaml")
log.Println("yamlFile:", yamlFile)
if err != nil {
log.Printf("yamlFile.Get err #%v ", err)
}
err = yaml.Unmarshal(yamlFile, conf)
// err = yaml.Unmarshal(yamlFile, &resultMap)
if err != nil {
log.Fatalf("Unmarshal: %v", err)
}
log.Println("conf", conf)
// log.Println("conf", resultMap)
}
總結
從main.go的代碼中可以看得出,當使用如test.yaml這種格式的yaml文件時,可以使用yaml.go中的Yaml和Yaml1這兩種struct來進行解析。當使用類似于test1.yaml這種格式的文件時,可以使用yaml.go中的Yaml2這種struct來進行解析。
個人理解,Yaml1與Yaml2的區別在于Yaml2中在tag中加入了inline
,使之變成了內嵌類型。
在官方的簡介中對于tag中支持的flag進行了說明,分別有flow
、inline
、omitempty
。其中flow
用于對數組進行解析,而omitempty
的作用在于當帶有此flag變量的值為nil或者零值的時候,則在Marshal之后的結果不會帶有此變量。
當然大家如果懶得去寫struct進行Unmarshal時,也是可以像main.go中直接聲明一個resultMap := make(map[string]interface{})
這樣來進行解析的。
本人第一次寫這類的文章,難免會有錯誤,請大家多多指教。