Golang解析yaml格式文件
前言
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{})
这样来进行解析的。
本文由 创作,采用 知识共享署名4.0 国际许可协议进行许可。本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。最后编辑时间为: 2020/06/28 09:30