1. json使用
JSON 應該比較熟悉,它是一種輕量級的數據交換格式。層次結構簡潔清晰 ,易于閱讀和編寫,同時也易于機器解析和生成。
- 創建 conf.json:
{"enabled": true,"path": "/usr/local"
}
- 新建config_json.go:
package mainimport ("encoding/json""fmt""os"
)type configuration struct {Enabled boolPath 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_Path\go\src\configmgr>go run config_json.go
path:/usr/local
2. ini的使用
INI文件格式是某些平臺或軟件上的配置文件的非正式標準,由節(section)和鍵(key)構成,比較常用于微軟Windows操作系統中。這種配置文件的文件擴展名為INI。
- 創建 conf.ini:
[Section]
enabled = true
path = /usr/local # another comment
2.下載第三方庫: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:\Go_Path\go\src\configmgr>go run config_ini.go
true
/usr/local
3. yaml使用
yaml 可能比較陌生一點,但是最近卻越來越流行。也就是一種標記語言。層次結構也特別簡潔清晰 ,易于閱讀和編寫,同時也易于機器解析和生成。
golang的標準庫中暫時沒有給我們提供操作yaml的標準庫,但是github上有很多優秀的第三方庫開源給我們使用。
- 創建 conf.yaml:
enabled: true
path: /usr/local
下載第三方庫:go get gopkg.in/yaml.v2
- 創建 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:\Go_Path\go\src\configmgr>go run config_yaml.go
path:/usr/local