本包提供了 Go 语言中读写 INI 文件的功能。
[]byte、文件和 io.ReadCloser)使用一个特定版本:
go get gopkg.in/ini.v1
使用最新版:
go get github.com/go-ini/ini
如需更新请添加 -u 选项。
如果您想要在自己的机器上运行测试,请使用 -t 标记:
go get -t gopkg.in/ini.v1
如需更新请添加 -u 选项。
一个 数据源 可以是 []byte 类型的原始数据,string 类型的文件路径或 io.ReadCloser。您可以加载 任意多个 数据源。如果您传递其它类型的数据源,则会直接返回错误。
cfg, err := ini.Load([]byte("raw data"), "filename", ioutil.NopCloser(bytes.NewReader([]byte("some other data"))))
或者从一个空白的文件开始:
cfg := ini.Empty()
当您在一开始无法决定需要加载哪些数据源时,仍可以使用 Append() 在需要的时候加载它们。
err := cfg.Append("other file", []byte("other raw data"))
当您想要加载一系列文件,但是不能够确定其中哪些文件是不存在的,可以通过调用函数 LooseLoad 来忽略它们(Load 会因为文件不存在而返回错误):
cfg, err := ini.LooseLoad("filename", "filename_404")
更牛逼的是,当那些之前不存在的文件在重新调用 Reload 方法的时候突然出现了,那么它们会被正常加载。
有时候分区和键的名称大小写混合非常烦人,这个时候就可以通过 InsensitiveLoad 将所有分区和键名在读取里强制转换为小写:
cfg, err := ini.InsensitiveLoad("filename")
//...
// sec1 和 sec2 指向同一个分区对象
sec1, err := cfg.GetSection("Section")
sec2, err := cfg.GetSection("SecTIOn")
// key1 和 key2 指向同一个键对象
key1, err := cfg.GetKey("Key")
key2, err := cfg.GetKey("KeY")
MySQL 的配置文件中会出现没有具体值的布尔类型的键:
[mysqld]
...
skip-host-cache
skip-name-resolve
默认情况下这被认为是缺失值而无法完成解析,但可以通过高级的加载选项对它们进行处理:
cfg, err := LoadSources(LoadOptions{AllowBooleanKeys: true}, "my.cnf"))
这些键的值永远为 true,且在保存到文件时也只会输出键名。
如果您想要通过程序来生成此类键,则可以使用 NewBooleanKey:
key, err := sec.NewBooleanKey("skip-host-cache")
下述几种情况的内容将被视为注释:
# 或 ; 开头的行# 或 ; 之后的内容[分区名] 之后的内容)如果你希望使用包含 # 或 ; 的值,请使用 ` 或 """ 进行包覆。
获取指定分区:
section, err := cfg.GetSection("section name")
如果您想要获取默认分区,则可以用空字符串代替分区名:
section, err := cfg.GetSection("")
当您非常确定某个分区是存在的,可以使用以下简便方法:
section := cfg.Section("section name")
如果不小心判断错了,要获取的分区其实是不存在的,那会发生什么呢?没事的,它会自动创建并返回一个对应的分区对象给您。
创建一个分区:
err := cfg.NewSection("new section")
获取所有分区对象或名称:
sections := cfg.Sections()
names := cfg.SectionStrings()
获取某个分区下的键:
key, err := cfg.Section("").GetKey("key name")
和分区一样,您也可以直接获取键而忽略错误处理:
key := cfg.Section("").Key("key name")
判断某个键是否存在:
yes := cfg.Section("").HasKey("key name")
创建一个新的键:
err := cfg.Section("").NewKey("name", "value")
获取分区下的所有键或键名:
keys := cfg.Section("").Keys()
names := cfg.Section("").KeyStrings()
获取分区下的所有键值对的克隆:
hash := cfg.Section("").KeysHash()
获取一个类型为字符串(string)的值:
val := cfg.Section("").Key("key name").String()
获取值的同时通过自定义函数进行处理验证:
val := cfg.Section("").Key("key name").Validate(func(in string) string {
if len(in) == 0 {
return "default"
}
return in
})
如果您不需要任何对值的自动转变功能(例如递归读取),可以直接获取原值(这种方式性能最佳):
val := cfg.Section("").Key("key name").Value()
判断某个原值是否存在:
yes := cfg.Section("").HasValue("test value")
获取其它类型的值:
// 布尔值的规则:
// true 当值为:1, t, T, TRUE, true, True, YES, yes, Yes, y, ON, on, On
// false 当值为:0, f, F, FALSE, false, False, NO, no, No, n, OFF, off, Off
v, err = cfg.Section("").Key("BOOL").Bool()
v, err = cfg.Section("").Key("FLOAT64").Float64()
v, err = cfg.Section("").Key("INT").Int()
v, err = cfg.Section("").Key("INT64").Int64()
v, err = cfg.Section("").Key("UINT").Uint()
v, err = cfg.Section("").Key("UINT64").Uint64()
v, err = cfg.Section("").Key("TIME").TimeFormat(time.RFC3339)
v, err = cfg.Section("").Key("TIME").Time() // RFC3339
v = cfg.Section("").Key("BOOL").MustBool()
v = cfg.Section("").Key("FLOAT64").MustFloat64()
v = cfg.Section("").Key("INT").MustInt()
v = cfg.Section("").Key("INT64").MustInt64()
v = cfg.Section("").Key("UINT").MustUint()
v = cfg.Section("").Key("UINT64").MustUint64()
v = cfg.Section("").Key("TIME").MustTimeFormat(time.RFC3339)
v = cfg.Section("").Key("TIME").MustTime() // RFC3339
// 由 Must 开头的方法名允许接收一个相同类型的参数来作为默认值,
// 当键不存在或者转换失败时,则会直接返回该默认值。
// 但是,MustString 方法必须传递一个默认值。
v = cfg.Seciont("").Key("String").MustString("default")
v = cfg.Section("").Key("BOOL").MustBool(true)
v = cfg.Section("").Key("FLOAT64").MustFloat64(1.25)
v = cfg.Section("").Key("INT").MustInt(10)
v = cfg.Section("").Key("INT64").MustInt64(99)
v = cfg.Section("").Key("UINT").MustUint(3)
v = cfg.Section("").Key("UINT64").MustUint64(6)
v = cfg.Section("").Key("TIME").MustTimeFormat(time.RFC3339, time.Now())
v = cfg.Section("").Key("TIME").MustTime(time.Now()) // RFC3339
如果我的值有好多行怎么办?
[advance]
ADDRESS = """404 road,
NotFound, State, 5000
Earth"""
嗯哼?小 case!
cfg.Section("advance").Key("ADDRESS").String()
/* --- start ---
404 road,
NotFound, State, 5000
Earth
------ end --- */
赞爆了!那要是我属于一行的内容写不下想要写到第二行怎么办?
[advance]
two_lines = how about \
continuation lines?
lots_of_lines = 1 \
2 \
3 \
4
简直是小菜一碟!
cfg.Section("advance").Key("two_lines").String() // how about continuation lines?
cfg.Section("advance").Key("lots_of_lines").String() // 1 2 3 4
可是我有时候觉得两行连在一起特别没劲,怎么才能不自动连接两行呢?
cfg, err := ini.LoadSources(ini.LoadOptions{
IgnoreContinuation: true,
}, "filename")
哇靠给力啊!
需要注意的是,值两侧的单引号会被自动剔除:
foo = "some value" // foo: some value
bar = 'some value' // bar: some value
这就是全部了?哈哈,当然不是。
获取键值时设定候选值:
v = cfg.Section("").Key("STRING").In("default", []string{"str", "arr", "types"})
v = cfg.Section("").Key("FLOAT64").InFloat64(1.1, []float64{1.25, 2.5, 3.75})
v = cfg.Section("").Key("INT").InInt(5, []int{10, 20, 30})
v = cfg.Section("").Key("INT64").InInt64(10, []int64{10, 20, 30})
v = cfg.Section("").Key("UINT").InUint(4, []int{3, 6, 9})
v = cfg.Section("").Key("UINT64").InUint64(8, []int64{3, 6, 9})
v = cfg.Section("").Key("TIME").InTimeFormat(time.RFC3339, time.Now(), []time.Time{time1, time2, time3})
v = cfg.Section("").Key("TIME").InTime(time.Now(), []time.Time{time1, time2, time3}) // RFC3339
如果获取到的值不是候选值的任意一个,则会返回默认值,而默认值不需要是候选值中的一员。
验证获取的值是否在指定范围内:
vals = cfg.Section("").Key("FLOAT64").RangeFloat64(0.0, 1.1, 2.2)
vals = cfg.Section("").Key("INT").RangeInt(0, 10, 20)
vals = cfg.Section("").Key("INT64").RangeInt64(0, 10, 20)
vals = cfg.Section("").Key("UINT").RangeUint(0, 3, 9)
vals = cfg.Section("").Key("UINT64").RangeUint64(0, 3, 9)
vals = cfg.Section("").Key("TIME").RangeTimeFormat(time.RFC3339, time.Now(), minTime, maxTime)
vals = cfg.Section("").Key("TIME").RangeTime(time.Now(), minTime, maxTime) // RFC3339
当存在无效输入时,使用零值代替:
// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4]
// Input: how, 2.2, are, you -> [0.0 2.2 0.0 0.0]
vals = cfg.Section("").Key("STRINGS").Strings(",")
vals = cfg.Section("").Key("FLOAT64S").Float64s(",")
vals = cfg.Section("").Key("INTS").Ints(",")
vals = cfg.Section("").Key("INT64S").Int64s(",")
vals = cfg.Section("").Key("UINTS").Uints(",")
vals = cfg.Section("").Key("UINT64S").Uint64s(",")
vals = cfg.Section("").Key("TIMES").Times(",")
从结果切片中剔除无效输入:
// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4]
// Input: how, 2.2, are, you -> [2.2]
vals = cfg.Section("").Key("FLOAT64S").ValidFloat64s(",")
vals = cfg.Section("").Key("INTS").ValidInts(",")
vals = cfg.Section("").Key("INT64S").ValidInt64s(",")
vals = cfg.Section("").Key("UINTS").ValidUints(",")
vals = cfg.Section("").Key("UINT64S").ValidUint64s(",")
vals = cfg.Section("").Key("TIMES").ValidTimes(",")
当存在无效输入时,直接返回错误: