知识点 操作yaml配置文件

go语言读取yaml文件
https://github.com/go-yaml/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{}) 这样来进行解析的。

posted @ 2019-08-16 16:52  初见未来  阅读(714)  评论(0编辑  收藏  举报