生活随笔
收集整理的這篇文章主要介紹了
Go-如何读取yaml,json,ini等配置文件
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1. json使用
JSON 應(yīng)該比較熟悉,它是一種輕量級(jí)的數(shù)據(jù)交換格式。層次結(jié)構(gòu)簡(jiǎn)潔清晰 ,易于閱讀和編寫(xiě),同時(shí)也易于機(jī)器解析和生成。
創(chuàng)建 conf.json:{"enabled": true,"path": "/usr/local"
}
新建config_json.go:package mainimport ("encoding/json""fmt""os"
)type configuration struct {Enabled boolPath string
}func main() {// 打開(kāi)文件file, _ := os.Open("conf.json")// 關(guān)閉文件defer file.Close()//NewDecoder創(chuàng)建一個(gè)從file讀取并解碼json對(duì)象的*Decoder,解碼器有自己的緩沖,并可能超前讀取部分json數(shù)據(jù)。decoder := json.NewDecoder(file)conf := configuration{}//Decode從輸入流讀取下一個(gè)json編碼值并保存在v指向的值里err := decoder.Decode(&conf)if err != nil {fmt.Println("Error:", err)}fmt.Println("path:" + conf.Path)
}
啟動(dòng)運(yùn)行后,輸出如下:
D:\Go_Path\go\src\configmgr>go run config_json.go
path:/usr/local
2. ini的使用
INI文件格式是某些平臺(tái)或軟件上的配置文件的非正式標(biāo)準(zhǔn),由節(jié)(section)和鍵(key)構(gòu)成,比較常用于微軟Windows操作系統(tǒng)中。這種配置文件的文件擴(kuò)展名為INI。
創(chuàng)建 conf.ini:[Section]
enabled = true
path = /usr/local # another comment
2.下載第三方庫(kù):go get gopkg.in/gcfg.v1
新建 config_ini.go:package mainimport ("fmt"gcfg "gopkg.in/gcfg.v1"
)func main() {config := struct {Section struct {Enabled boolPath string}}{}err := gcfg.ReadFileInto(&config, "conf.ini")if err != nil {fmt.Println("Failed to parse config file: %s", err)}fmt.Println(config.Section.Enabled)fmt.Println(config.Section.Path)
}
啟動(dòng)運(yùn)行后,輸出如下:
D:\Go_Path\go\src\configmgr>go run config_ini.go
true
/usr/local
3. yaml使用
yaml 可能比較陌生一點(diǎn),但是最近卻越來(lái)越流行。也就是一種標(biāo)記語(yǔ)言。層次結(jié)構(gòu)也特別簡(jiǎn)潔清晰 ,易于閱讀和編寫(xiě),同時(shí)也易于機(jī)器解析和生成。
golang的標(biāo)準(zhǔn)庫(kù)中暫時(shí)沒(méi)有給我們提供操作yaml的標(biāo)準(zhǔn)庫(kù),但是github上有很多優(yōu)秀的第三方庫(kù)開(kāi)源給我們使用。
創(chuàng)建 conf.yaml:enabled: true
path: /usr/local
下載第三方庫(kù):go get gopkg.in/yaml.v2
創(chuàng)建 config_yaml.go:package mainimport ("fmt""io/ioutil""log""gopkg.in/yaml.v2"
)type conf struct {Enabled bool `yaml:"enabled"` //yaml:yaml格式 enabled:屬性的為enabledPath string `yaml:"path"`
}func (c *conf) getConf() *conf {yamlFile, err := ioutil.ReadFile("conf.yaml")if err != nil {log.Printf("yamlFile.Get err #%v ", err)}err = yaml.Unmarshal(yamlFile, c)if err != nil {log.Fatalf("Unmarshal: %v", err)}return c
}func main() {var c confc.getConf()fmt.Println("path:" + c.Path)
}
啟動(dòng)運(yùn)行后,輸出如下:
D:\Go_Path\go\src\configmgr>go run config_yaml.go
path:/usr/local
轉(zhuǎn)載于:https://www.cnblogs.com/Paul-watermelon/p/11228008.html
總結(jié)
以上是生活随笔為你收集整理的Go-如何读取yaml,json,ini等配置文件的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。