yaml
文件是现在很流行的一种配置文件,具有结构清晰,层次分明的特点。下面主要给大家介绍关于Golang
解析yaml
的具体方法。
导入依赖
go get gopkg.in/yaml.v3
config.yaml文件内容如下
database:
mysql: 127.0.0.1
es:
host: 127.0.0.1
user: es
pwd: 123
实例代码
// main.go
package main
import (
"fmt"
"io/ioutil"
"gopkg.in/yaml.v2"
)
type Conf struct {
Database Database `yaml:"database"`
Es Es `yaml:"es"`
}
type Database struct {
Mysql string `yaml:"mysql"`
}
type Es struct {
Host string `yaml:"host"`
User string `yaml:"user"`
Pwd string `yaml:"pwd"`
}
//读取yaml配置文件方法
func getConf() Conf {
var conf Conf
yamlFile, err := ioutil.ReadFile("./config.yaml")
if err != nil {
fmt.Println(err.Error())
}
err = yaml.Unmarshal(yamlFile, &conf)
if err != nil {
fmt.Println(err.Error())
}
return conf
}
func main() {
fmt.Println(getConf().Database)
fmt.Println(getConf().Database.Mysql)
}