c读取ini配置文件_Go-INI - 超赞的Go语言INI文件操作库
INI 文件(Initialization File)是十分常用的配置文件格式,其由節(section)、鍵(key)和值(value)組成,編寫方便,表達性強,并能實現基本的配置分組功能,被各類軟件框架和項目廣泛使用。然而,日漸受到關注的 Go 語言,其官方庫并沒有對 INI 文件操作的庫,而進行 INI 文件的解析也并不是幾行就能完成的簡單工作。Go-INI,就為 Go 語言添加了對 INI 文件進行讀取、解析和寫入等操作,使得 Go 項目也能充分利用 INI 文件的便利性。
Go-INI 庫
簡介
Go-INI,是 go-ini 在 Github 上開源的 Go 語言 INI 文件操作庫,項目位于 https://github.com/go-ini/ini,目前版本為 1.61.0。Go-INIT 功能強大,支持豐富的 INI 語法,功能特性包括:
- 支持覆蓋加載多個數據源(file, []byte, io.Reader and io.ReadCloser)
- 支持遞歸讀取鍵值
- 支持讀取父子分區
- 支持讀取自增鍵名
- 支持讀取多行的鍵值
- 支持大量輔助方法
- 支持在讀取時直接轉換為 Go 語言類型
- 支持讀取和 寫入 分區和鍵的注釋
- 輕松操作分區、鍵值和注釋
- 在保存文件時分區和鍵值會保持原有的順序
- ……
Go-INI Github項目
安裝
Go-INI 要求 Go 1.6+,使用 go get 安裝:
$ go get gopkg.in/ini.v1Go-INI特性
示例
我們來看一個簡單的使用例子。首先,創建一個 INI 文件 my.ini:
# possible values : production, developmentapp_mode = development[paths]# Path to where grafana can store temp files, sessions, and the sqlite3 db (if that is used)data = /home/git/grafana[server]# Protocol (http or https)protocol = http?# The http port to usehttp_port = 9999?# Redirect to correct domain if host header does not match domain# Prevents DNS rebinding attacksenforce_domain = true這是一個十分常見的 INI 配置文件。然后,我們使用 Go-INIT 來進行操作:
package main?import ( ? "fmt" ? "os"? ? "gopkg.in/ini.v1")?func main() { ? cfg, err := ini.Load("my.ini") ? if err != nil { ? ? ? fmt.Printf("Fail to read file: %v", err) ? ? ? os.Exit(1) ? }? ? // 典型讀取操作,默認分區可以使用空字符串表示 ? fmt.Println("App Mode:", cfg.Section("").Key("app_mode").String()) ? fmt.Println("Data Path:", cfg.Section("paths").Key("data").String())? ? // 我們可以做一些候選值限制的操作 ? fmt.Println("Server Protocol:", ? ? ? cfg.Section("server").Key("protocol").In("http", []string{"http", "https"})) ? // 如果讀取的值不在候選列表內,則會回退使用提供的默認值 ? fmt.Println("Email Protocol:", ? ? ? cfg.Section("server").Key("protocol").In("smtp", []string{"imap", "smtp"}))? ? // 試一試自動類型轉換 ? fmt.Printf("Port Number: (%[1]T) %[1]d", cfg.Section("server").Key("http_port").MustInt(9999)) ? fmt.Printf("Enforce Domain: (%[1]T) %[1]v", cfg.Section("server").Key("enforce_domain").MustBool(false))? ? // 修改某個值然后進行保存 ? cfg.Section("").Key("app_mode").SetValue("production") ? cfg.SaveTo("my.ini.local")}我們來看一看這段代碼做了什么。首先,進行了 Go-INI 的引入:
import "gopkg.in/ini.v1"然后,使用 Load 接口,進行 INI 文件的打開、加載和解析。Load 的函數定義如下:
func Load(source interface{}, others ...interface{}) (*File, error) {Load 的 source 參數使用 interface{} 類型,允許多種類型的數據源,包括字符串類型的文件名、[]byte 類型的原數據等。Load 返回一個 *File 類型的文件指針,和一個錯誤信息。 然后,可以使用 Go-INI 提供的 Section 接口,獲取 INI 文件的節:
func (f *File) Section(name string) *Section再利用 Section 的 Key 接口,實現對于參數值的獲取:
func (s *Section) Key(name string) *Key返回一個 Key 結構體,然后再利用 Key 的 String 接口,獲取對應的字符串類型的值:
func (k *Key) String() string有時候,我們需要對于配置值的值進行驗證,當值不在預選列表里時,需要返回一個默認值,而不是一個無效的值。這時,可以使用 Key 的 In 接口實現:
func (k *Key) In(defaultVal string, candidates []string) stringGo-INI 還可以進行值的類型轉換:
func (k *Key) MustInt(defaultVal ...int) int最后,使用 Key 的 SetValue 進行值得設置,然后使用 SaveTo 重新寫入文件:
func (k *Key) SetValue(v string)func (f *File) SaveTo(filename string) error運行上述代碼,我們可以得到以下輸出:
$ go run main.goApp Mode: developmentData Path: /home/git/grafanaServer Protocol: httpEmail Protocol: smtpPort Number: (int) 9999Enforce Domain: (bool) true此外,Go-INI 還提供了 INI 文件和結構體之間的映射。當配置文件是固定的時候,在代碼中定義一個結構體,可以使得對配置的操作更為方便。使用前綴為 ini 的結構體標簽,就可以實現 INI 文件和結構體的雙向映射:
type Embeded struct { ? Dates []time.Time `delim:"|" comment:"Time data"` ? Places []string ? `ini:"places,omitempty"` ? None ? []int ? ? ? `ini:",omitempty"`}?type Author struct { ? Name ? ? string `ini:"NAME"` ? Male ? ? bool ? Age ? ? ? int `comment:"Author's age"` ? GPA ? ? ? float64 ? NeverMind string `ini:"-"` ? *Embeded `comment:"Embeded section"`}?func main() { ? a := &Author{"Unknwon", true, 21, 2.8, "", ? ? ? &Embeded{ ? ? ? ? ? []time.Time{time.Now(), time.Now()}, ? ? ? ? ? []string{"HangZhou", "Boston"}, ? ? ? ? ? []int{}, ? ? ? }} ? cfg := ini.Empty() ? err = ini.ReflectFrom(cfg, a) ? // ...}Go-INI
總結
Go-INI 作為 Go 語言的 INI 文件操作庫,提供了豐富的 INI 文件操作,使得 Go 項目也能應用 INI 配置文件,為大量的已有項目提供了極大的便利,是使用 INI 文件的 Go 項目必備的依賴庫。
總結
以上是生活随笔為你收集整理的c读取ini配置文件_Go-INI - 超赞的Go语言INI文件操作库的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python计算题_python计算题
- 下一篇: c语言位运算_C语言自增减、逻辑运算、位