实际项目中,读取相关的系统配置文件是很常见的事情。今天就来说一说,Golang 是如何读取YAML,JSON,INI等配置文件的。

 

JSON 应该比较熟悉,它是一种轻量级的数据交换格式。层次结构简洁清晰 ,易于阅读和编写,同时也易于机器解析和生成。

  1. 创建 conf.json:

  1. {
  2. "enabled": true,
  3. "path": "/usr/local"
  4. }

 

  2. 新建config_json.go:

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "os"
  6. )
  7. type configuration struct {
  8. Enabled bool
  9. Path string
  10. }
  11. func main() {
  12. // 打开文件
  13. file, _ := os.Open("conf.json")
  14. // 关闭文件
  15. defer file.Close()
  16. //NewDecoder创建一个从file读取并解码json对象的*Decoder,解码器有自己的缓冲,并可能超前读取部分json数据。
  17. decoder := json.NewDecoder(file)
  18. conf := configuration{}
  19. //Decode从输入流读取下一个json编码值并保存在v指向的值里
  20. err := decoder.Decode(&conf)
  21. if err != nil {
  22. fmt.Println("Error:", err)
  23. }
  24. fmt.Println("path:" + conf.Path)
  25. }

 

  启动运行后,输出如下:

  1. D:\Go_Path\go\src\configmgr>go run config_json.go
  2. path:/usr/local

 

INI文件格式是某些平台或软件上的配置文件的非正式标准,由节(section)和键(key)构成,比较常用于微软Windows操作系统中。这种配置文件的文件扩展名为INI。

  1. 创建 conf.ini:

  1. [Section]
  2. enabled = true
  3. path = /usr/local # another comment

  2.下载第三方库:go get gopkg.in/gcfg.v1

  3. 新建 config_ini.go:

  1. package main
  2. import (
  3. "fmt"
  4. gcfg "gopkg.in/gcfg.v1"
  5. )
  6. func main() {
  7. config := struct {
  8. Section struct {
  9. Enabled bool
  10. Path string
  11. }
  12. }{}
  13. err := gcfg.ReadFileInto(&config, "conf.ini")
  14. if err != nil {
  15. fmt.Println("Failed to parse config file: %s", err)
  16. }
  17. fmt.Println(config.Section.Enabled)
  18. fmt.Println(config.Section.Path)
  19. }

 

  启动运行后,输出如下:

  1. D:\Go_Path\go\src\configmgr>go run config_ini.go
  2. true
  3. /usr/local

 

yaml 可能比较陌生一点,但是最近却越来越流行。也就是一种标记语言。层次结构也特别简洁清晰 ,易于阅读和编写,同时也易于机器解析和生成。

golang的标准库中暂时没有给我们提供操作yaml的标准库,但是github上有很多优秀的第三方库开源给我们使用。

  1. 创建 conf.yaml:

  1. enabled: true
  2. path: /usr/local

  2. 下载第三方库:go get  gopkg.in/yaml.v2

  3. 创建 config_yaml.go:

  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "log"
  6.  
  7. "gopkg.in/yaml.v2"
  8. )
  9. type conf struct {
  10. Enabled bool `yaml:"enabled"` //yaml:yaml格式 enabled:属性的为enabled
  11. Path string `yaml:"path"`
  12. }
  13. func (c *conf) getConf() *conf {
  14. yamlFile, err := ioutil.ReadFile("conf.yaml")
  15. if err != nil {
  16. log.Printf("yamlFile.Get err #%v ", err)
  17. }
  18. err = yaml.Unmarshal(yamlFile, c)
  19. if err != nil {
  20. log.Fatalf("Unmarshal: %v", err)
  21. }
  22. return c
  23. }
  24. func main() {
  25. var c conf
  26. c.getConf()
  27. fmt.Println("path:" + c.Path)
  28. }

 

  启动运行后,输出如下:

  1. D:\Go_Path\go\src\configmgr>go run config_yaml.go
  2. path:/usr/local

 

以上,就把golang 读取配置文件的方法,都介绍完了。大家可以拿着代码运行起来看看。

 

版权声明:本文为zhangweizhong原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/zhangweizhong/p/10505158.html