c读取ini配置文件_Go-INI - 超赞的Go语言INI文件操作库
INI 文件(Initialization File)是十分常用的配置文件格式,其由節(jié)(section)、鍵(key)和值(value)組成,編寫方便,表達(dá)性強(qiáng),并能實(shí)現(xiàn)基本的配置分組功能,被各類軟件框架和項(xiàng)目廣泛使用。然而,日漸受到關(guān)注的 Go 語言,其官方庫并沒有對(duì) INI 文件操作的庫,而進(jìn)行 INI 文件的解析也并不是幾行就能完成的簡單工作。Go-INI,就為 Go 語言添加了對(duì) INI 文件進(jìn)行讀取、解析和寫入等操作,使得 Go 項(xiàng)目也能充分利用 INI 文件的便利性。
Go-INI 庫
簡介
Go-INI,是 go-ini 在 Github 上開源的 Go 語言 INI 文件操作庫,項(xiàng)目位于 https://github.com/go-ini/ini,目前版本為 1.61.0。Go-INIT 功能強(qiáng)大,支持豐富的 INI 語法,功能特性包括:
- 支持覆蓋加載多個(gè)數(shù)據(jù)源(file, []byte, io.Reader and io.ReadCloser)
- 支持遞歸讀取鍵值
- 支持讀取父子分區(qū)
- 支持讀取自增鍵名
- 支持讀取多行的鍵值
- 支持大量輔助方法
- 支持在讀取時(shí)直接轉(zhuǎn)換為 Go 語言類型
- 支持讀取和 寫入 分區(qū)和鍵的注釋
- 輕松操作分區(qū)、鍵值和注釋
- 在保存文件時(shí)分區(qū)和鍵值會(huì)保持原有的順序
- ……
Go-INI Github項(xiàng)目
安裝
Go-INI 要求 Go 1.6+,使用 go get 安裝:
$ go get gopkg.in/ini.v1Go-INI特性
示例
我們來看一個(gè)簡單的使用例子。首先,創(chuàng)建一個(gè) 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這是一個(gè)十分常見的 INI 配置文件。然后,我們使用 Go-INIT 來進(jìn)行操作:
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) ? }? ? // 典型讀取操作,默認(rèn)分區(qū)可以使用空字符串表示 ? 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"})) ? // 如果讀取的值不在候選列表內(nèi),則會(huì)回退使用提供的默認(rèn)值 ? fmt.Println("Email Protocol:", ? ? ? cfg.Section("server").Key("protocol").In("smtp", []string{"imap", "smtp"}))? ? // 試一試自動(dòng)類型轉(zhuǎn)換 ? 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))? ? // 修改某個(gè)值然后進(jìn)行保存 ? cfg.Section("").Key("app_mode").SetValue("production") ? cfg.SaveTo("my.ini.local")}我們來看一看這段代碼做了什么。首先,進(jìn)行了 Go-INI 的引入:
import "gopkg.in/ini.v1"然后,使用 Load 接口,進(jìn)行 INI 文件的打開、加載和解析。Load 的函數(shù)定義如下:
func Load(source interface{}, others ...interface{}) (*File, error) {Load 的 source 參數(shù)使用 interface{} 類型,允許多種類型的數(shù)據(jù)源,包括字符串類型的文件名、[]byte 類型的原數(shù)據(jù)等。Load 返回一個(gè) *File 類型的文件指針,和一個(gè)錯(cuò)誤信息。 然后,可以使用 Go-INI 提供的 Section 接口,獲取 INI 文件的節(jié):
func (f *File) Section(name string) *Section再利用 Section 的 Key 接口,實(shí)現(xiàn)對(duì)于參數(shù)值的獲取:
func (s *Section) Key(name string) *Key返回一個(gè) Key 結(jié)構(gòu)體,然后再利用 Key 的 String 接口,獲取對(duì)應(yīng)的字符串類型的值:
func (k *Key) String() string有時(shí)候,我們需要對(duì)于配置值的值進(jìn)行驗(yàn)證,當(dāng)值不在預(yù)選列表里時(shí),需要返回一個(gè)默認(rèn)值,而不是一個(gè)無效的值。這時(shí),可以使用 Key 的 In 接口實(shí)現(xiàn):
func (k *Key) In(defaultVal string, candidates []string) stringGo-INI 還可以進(jìn)行值的類型轉(zhuǎn)換:
func (k *Key) MustInt(defaultVal ...int) int最后,使用 Key 的 SetValue 進(jìn)行值得設(shè)置,然后使用 SaveTo 重新寫入文件:
func (k *Key) SetValue(v string)func (f *File) SaveTo(filename string) error運(yùn)行上述代碼,我們可以得到以下輸出:
$ go run main.goApp Mode: developmentData Path: /home/git/grafanaServer Protocol: httpEmail Protocol: smtpPort Number: (int) 9999Enforce Domain: (bool) true此外,Go-INI 還提供了 INI 文件和結(jié)構(gòu)體之間的映射。當(dāng)配置文件是固定的時(shí)候,在代碼中定義一個(gè)結(jié)構(gòu)體,可以使得對(duì)配置的操作更為方便。使用前綴為 ini 的結(jié)構(gòu)體標(biāo)簽,就可以實(shí)現(xiàn) INI 文件和結(jié)構(gòu)體的雙向映射:
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
總結(jié)
Go-INI 作為 Go 語言的 INI 文件操作庫,提供了豐富的 INI 文件操作,使得 Go 項(xiàng)目也能應(yīng)用 INI 配置文件,為大量的已有項(xiàng)目提供了極大的便利,是使用 INI 文件的 Go 項(xiàng)目必備的依賴庫。
總結(jié)
以上是生活随笔為你收集整理的c读取ini配置文件_Go-INI - 超赞的Go语言INI文件操作库的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python计算题_python计算题
- 下一篇: c语言位运算_C语言自增减、逻辑运算、位