1、新建 conf.yaml 文件
database: dbtype: mysql dbname: database table: table username: username password: password application: port: 8000
2、新建 conf.go 文件
//package conf package main import ( "fmt" "io/ioutil" "gopkg.in/yaml.v2" ) type Conf struct { Database Database Application Application } type Database struct { Dbtype string Dbname string Table string Username string Password string } type Application struct { Port string } func GetConf() Conf { var conf Conf
// 加载文件 yamlFile, err := ioutil.ReadFile("/Users/root/Desktop/home/workStations/GoProjects/src/oa.yuchan.cn/conf/conf.yaml") if err != nil { fmt.Println(err.Error()) }
// 将读取的yaml文件解析为响应的 struct err = yaml.Unmarshal(yamlFile, &conf) if err != nil { fmt.Println(err.Error()) } return conf } func main() { fmt.Println(GetConf().Database.Dbname) }