日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Go-如何读取yaml,json,ini等配置文件

發布時間:2023/11/29 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Go-如何读取yaml,json,ini等配置文件 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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

    轉載于:https://www.cnblogs.com/Paul-watermelon/p/11228008.html

    總結

    以上是生活随笔為你收集整理的Go-如何读取yaml,json,ini等配置文件的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。