實際項目中,還有一個比較重要的基礎功能,就是讀取相關的配置文件。今天就來說一說,Golang 是如何讀取YAML,JSON,INI等配置文件的。
1. json使用
JSON 應該比較熟悉,它是一種輕量級的數據交換格式。層次結構簡潔清晰 ,易于閱讀和編寫,同時也易于機器解析和生成。
1. 創建 conf.json:
{
"enabled": true,
"path": "/usr/local"
}
2. 新建config_json.go:
package main
import (
"encoding/json"
"fmt"
"os"
)
type configuration struct {
Enabled bool
Path string
}
func main() {
// 打開文件
file, _ := os.Open("conf.json")
// 關閉文件
defer file.Close()
//NewDecoder創建一個從file讀取并解碼json對象的*Decoder,解碼器有自己的緩沖,并可能超前讀取部分json數據。
decoder := json.NewDecoder(file)
conf := configuration{}
//Decode從輸入流讀取下一個json編碼值并保存在v指向的值里
err := decoder.Decode(&conf)
if err != nil {
fmt.Println("Error:", err)
}
fmt.Println("path:" + conf.Path)
}
啟動運行后,輸出如下:
D:Go_Pathgosrcconfigmgr>go run config_json.go path:/usr/local
2. ini的使用
INI文件格式是某些平臺或軟件上的配置文件的非正式標準,由節(section)和鍵(key)構成,比較常用于微軟windows操作系統中。這種配置文件的文件擴展名為INI。
1. 創建 conf.ini:
[Section] enabled = true path = /usr/local # another comment
2.下載第三方庫:go get gopkg.in/gcfg.v1
3. 新建 config_ini.go:
package main
import (
"fmt"
gcfg "gopkg.in/gcfg.v1"
)
func main() {
config := struct {
Section struct {
Enabled bool
Path 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:Go_Pathgosrcconfigmgr>go run config_ini.go true /usr/local
3. yaml使用
yaml 可能比較陌生一點,但是最近卻越來越流行。也就是一種標記語言。層次結構也特別簡潔清晰 ,易于閱讀和編寫,同時也易于機器解析和生成。
golang的標準庫中暫時沒有給我們提供操作yaml的標準庫,但是github上有很多優秀的第三方庫開源給我們使用。
1. 創建 conf.yaml:
enabled: true path: /usr/local
2. 下載第三方庫:go get gopkg.in/yaml.v2
3. 創建 config_yaml.go:
package main
import (
"fmt"
"io/ioutil"
"log"
"gopkg.in/yaml.v2"
)
type conf struct {
Enabled bool `yaml:"enabled"` //yaml:yaml格式 enabled:屬性的為enabled
Path 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 conf
c.getConf()
fmt.Println("path:" + c.Path)
}
啟動運行后,輸出如下:
D:Go_Pathgosrcconfigmgr>go run config_yaml.go path:/usr/local






