[GoLang]使用yaml.v2解析配置文件记录
freddon
发表于2018-12-12
阅读 2273 |
评论 0
记录使用Go环境下,如何使用yaml.v2读取yml配置转为结构体
### 安装 yaml.v2
---
```sh
go get -u gopkg.in/yaml.v2
```
### 准备工作
---
1. 一份yml配置文档,类似如下:
__config.xml__
```yml
app:
mode: develop
logLevel: verbose
databases:
mysql001:
database: sagocloud
user : root
password : 123456
host : 127.0.0.1
port : 3306
redis001:
database: 6
password: 123456
host: 127.0.0.1
port : 6379
```
2.编写解析配置文件的go文件
__config.go__
```go
package tools
import (
"io/ioutil"
"log"
"gopkg.in/yaml.v2"
)
// DB 数据库基本配置
type DB struct {
Database string `yaml:"database"`
User string `yaml:"user"`
Password string `yaml:"password"`
Host string `yaml:"host"`
Port int16 `yaml:"port"`
}
// Config 环境基础配置
type Config struct {
App struct {
Mode string `yaml:"mode"`
LogLevel string `yaml:"logLevel"`
}
Databases struct {
Mysql DB `yaml:"mysql001"`
Redis DB `yaml:"redis001"`
} `yaml:"databases"`
}
func (c *Config) _Init() *Config {
yamlFile, err := ioutil.ReadFile("config.yml")
if err != nil {
log.Printf("yamlFile.Get err #%v ", err)
}
yamlError := yaml.Unmarshal(yamlFile, c)
if yamlError != nil {
log.Printf("yamlFile.Get err #%v ", yamlError)
}
return c
}
// GetConfig 读取运行环境基础配置
func GetConfig() *Config {
var c Config
return c._Init()
}
```
3.测试
__main.go__
```go
package main
import (
"log"
"sagocloud.com/deciigo/tools"
)
func main() {
c := tools.GetConfig()
log.Println(c)
}
```
我是通过VS Code打断点debug查看最终解析出得结构体的,放张图:

PS:在struct中声明的变量如果不是大写字母开头,yaml会解析不上去(请看上图中的host,我改为小写后的情况),我还没读源码,不过一般都是大写开头吧,跟别的语言规则不一样。
分类 :日常记录