在Go語言項(xiàng)目中,常用的配置文件yaml、toml、json、xml、ini幾種,因?yàn)楸菊轮饕v解yaml配置文件的使用方法,其他幾種配置文件在這里就不展開了介紹了,大家有興趣可以自行百度。
yaml文件的語法網(wǎng)上有很多的教程,大家自行百度,這里也推薦兩個(gè)鏈接:
- 快速了解:https://cloud.tencent.com/developer/article/1474944
- 系統(tǒng)學(xué)習(xí):https://www.yiibai.com/yaml/yaml_basics.html
yaml文件解析使用的是github上第三方開源框架gopkg.in/yaml.v2,下面詳細(xì)介紹安裝和使用的方法:
1. 在項(xiàng)目的根目錄執(zhí)行如下命令:
go get gopkg.in/yaml.v2
2. 在項(xiàng)目的根目錄創(chuàng)建conf.yaml
文件,并添加以下內(nèi)容:
service:
url: https://127.0.0.1:8080
host: 127.0.0.1
subscriptions: [{
topic: "orders_create",
address: "https://127.0.0.1:8080/orders/creat"
},{
topic: "orders_submit",
address: "https://127.0.0.1:8080/orders/submit"
}
]
3. 在項(xiàng)目的main.go文件中導(dǎo)入頭文件:
import (
...
"gopkg.in/yaml.v2"
...
)
4. 創(chuàng)建struct數(shù)據(jù)結(jié)構(gòu):
//定義conf類型
//類型里的屬性,全是配置文件里的屬性
type Conf struct {
Service Serivce `yaml:"service"`
}
type Serivce struct {
Url string `yaml:"url"`
Host string `yaml:"host"`
Topics []Topic `yaml:"subscriptions"`
}
type Topic struct {
Topic string `yaml:"topic"`
Address string `yaml:"address"`
}
5. 添加讀取配置文件以及解析數(shù)據(jù)結(jié)構(gòu)的代碼:
//讀取Yaml配置文件,
//并轉(zhuǎn)換成conf對象
func (conf *Conf) getConf() *Conf {
//應(yīng)該是 絕對地址
yamlFile, err := ioutil.ReadFile("conf.yaml")
if err != nil {
fmt.Println(err.Error())
}
err = yaml.Unmarshal(yamlFile, conf)
if err != nil {
fmt.Println(err.Error())
}
return conf
}
6. 在程序中調(diào)用配置讀取的接口并打印輸出:
func main() {
var conf Conf
conf.getConf()
var service = conf.Serivce
fmt.Println("Shopify Url=" + service.Url)
fmt.Println("Shopify Version=" + service.Host)
}
參考鏈接:https://blog.csdn.net/wade3015/article/details/83351776