INI 文件(Initialization File)是十分常用的配置文件格式,其由节(section)、键(key)和值(value)组成,编写方便,表达性强,并能实现基本的配置分组功能,被各类软件框架和项目广泛使用。然而,日渐受到关注的 Go 语言,其官方库并没有对 INI 文件操作的库,而进行 INI 文件的解析也并不是几行就能完成的简单工作。Go-INI,就为 Go 语言添加了对 INI 文件进行读取、解析和写入等操作,使得 Go 项目也能充分利用 INI 文件的便利性。
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5yN3QzNmVmN5UTOlZWZhRDMkJWMhRGMxEzMiJGZwIWOj9CX0JXZ252bj91Ztl2Lc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
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.v1
Go-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 mainimport ( "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 的函数定义如下:
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) string
Go-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 项目必备的依赖库。