1. 安装第三方组件
go get gopkg.in/yaml.v2
2. 使用范例:
yaml文件内容:
database:
host: 127.0.0.1
username:
password:
定义对应struct容器:
type Conf struct {
Database struct{
Host string `yaml:"host"`
UserName string `yaml:"username"`
Password string `yaml:"password"`
}
}
处理代码:
configFile, err := ioutil.ReadFile("/home/user/go/src/gin_test/config/config.yml")
if err != nil{
context.JSON(http.StatusOK, gin.H{
"msg" : "System error:can not find the file",
})
}
conf := Conf{}
err = yaml.Unmarshal(configFile, &conf)
if err != nil{
context.JSON(http.StatusOK, gin.H{
"msg" : "System error:format wrong",
})
}
host := conf.Database.Host