亚洲视频二区_亚洲欧洲日本天天堂在线观看_日韩一区二区在线观看_中文字幕不卡一区

公告:魔扣目錄網為廣大站長提供免費收錄網站服務,提交前請做好本站友鏈:【 網站目錄:http://www.430618.com 】, 免友鏈快審服務(50元/站),

點擊這里在線咨詢客服
新站提交
  • 網站:51998
  • 待審:31
  • 小程序:12
  • 文章:1030137
  • 會員:747

如何讀取yaml,json,ini等配置文件

 

實際項目中,還有一個比較重要的基礎功能,就是讀取相關的配置文件。今天就來說一說,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

分享到:
標簽:json
用戶無頭像

網友整理

注冊時間:

網站:5 個   小程序:0 個  文章:12 篇

  • 51998

    網站

  • 12

    小程序

  • 1030137

    文章

  • 747

    會員

趕快注冊賬號,推廣您的網站吧!
最新入駐小程序

數獨大挑戰2018-06-03

數獨一種數學游戲,玩家需要根據9

答題星2018-06-03

您可以通過答題星輕松地創建試卷

全階人生考試2018-06-03

各種考試題,題庫,初中,高中,大學四六

運動步數有氧達人2018-06-03

記錄運動步數,積累氧氣值。還可偷

每日養生app2018-06-03

每日養生,天天健康

體育訓練成績評定2018-06-03

通用課目體育訓練成績評定