1 本包提供了 Go 语言中读写 INI 文件的功能。
5 - 支持覆盖加载多个数据源(`[]byte`、文件和 `io.ReadCloser`)
12 - 支持读取和 **写入** 分区和键的注释
20 go get gopkg.in/ini.v1
24 go get github.com/go-ini/ini
30 如果您想要在自己的机器上运行测试,请使用 `-t` 标记:
32 go get -t gopkg.in/ini.v1
40 一个 **数据源** 可以是 `[]byte` 类型的原始数据,`string` 类型的文件路径或 `io.ReadCloser`。您可以加载 **任意多个** 数据源。如果您传递其它类型的数据源,则会直接返回错误。
43 cfg, err := ini.Load([]byte("raw data"), "filename", ioutil.NopCloser(bytes.NewReader([]byte("some other data"))))
52 当您在一开始无法决定需要加载哪些数据源时,仍可以使用 **Append()** 在需要的时候加载它们。
55 err := cfg.Append("other file", []byte("other raw data"))
58 当您想要加载一系列文件,但是不能够确定其中哪些文件是不存在的,可以通过调用函数 `LooseLoad` 来忽略它们(`Load` 会因为文件不存在而返回错误):
61 cfg, err := ini.LooseLoad("filename", "filename_404")
64 更牛逼的是,当那些之前不存在的文件在重新调用 `Reload` 方法的时候突然出现了,那么它们会被正常加载。
68 有时候分区和键的名称大小写混合非常烦人,这个时候就可以通过 `InsensitiveLoad` 将所有分区和键名在读取里强制转换为小写:
71 cfg, err := ini.InsensitiveLoad("filename")
74 // sec1 和 sec2 指向同一个分区对象
75 sec1, err := cfg.GetSection("Section")
76 sec2, err := cfg.GetSection("SecTIOn")
78 // key1 和 key2 指向同一个键对象
79 key1, err := cfg.GetKey("Key")
80 key2, err := cfg.GetKey("KeY")
83 #### 类似 MySQL 配置中的布尔值键
85 MySQL 的配置文件中会出现没有具体值的布尔类型的键:
94 默认情况下这被认为是缺失值而无法完成解析,但可以通过高级的加载选项对它们进行处理:
97 cfg, err := LoadSources(LoadOptions{AllowBooleanKeys: true}, "my.cnf"))
100 这些键的值永远为 `true`,且在保存到文件时也只会输出键名。
102 如果您想要通过程序来生成此类键,则可以使用 `NewBooleanKey`:
105 key, err := sec.NewBooleanKey("skip-host-cache")
112 1. 所有以 `#` 或 `;` 开头的行
113 2. 所有在 `#` 或 `;` 之后的内容
114 3. 分区标签后的文字 (即 `[分区名]` 之后的内容)
116 如果你希望使用包含 `#` 或 `;` 的值,请使用 ``` ` ``` 或 ``` """ ``` 进行包覆。
123 section, err := cfg.GetSection("section name")
126 如果您想要获取默认分区,则可以用空字符串代替分区名:
129 section, err := cfg.GetSection("")
132 当您非常确定某个分区是存在的,可以使用以下简便方法:
135 section := cfg.Section("section name")
138 如果不小心判断错了,要获取的分区其实是不存在的,那会发生什么呢?没事的,它会自动创建并返回一个对应的分区对象给您。
143 err := cfg.NewSection("new section")
149 sections := cfg.Sections()
150 names := cfg.SectionStrings()
158 key, err := cfg.Section("").GetKey("key name")
161 和分区一样,您也可以直接获取键而忽略错误处理:
164 key := cfg.Section("").Key("key name")
170 yes := cfg.Section("").HasKey("key name")
176 err := cfg.Section("").NewKey("name", "value")
182 keys := cfg.Section("").Keys()
183 names := cfg.Section("").KeyStrings()
189 hash := cfg.Section("").KeysHash()
194 获取一个类型为字符串(string)的值:
197 val := cfg.Section("").Key("key name").String()
203 val := cfg.Section("").Key("key name").Validate(func(in string) string {
211 如果您不需要任何对值的自动转变功能(例如递归读取),可以直接获取原值(这种方式性能最佳):
214 val := cfg.Section("").Key("key name").Value()
220 yes := cfg.Section("").HasValue("test value")
227 // true 当值为:1, t, T, TRUE, true, True, YES, yes, Yes, y, ON, on, On
228 // false 当值为:0, f, F, FALSE, false, False, NO, no, No, n, OFF, off, Off
229 v, err = cfg.Section("").Key("BOOL").Bool()
230 v, err = cfg.Section("").Key("FLOAT64").Float64()
231 v, err = cfg.Section("").Key("INT").Int()
232 v, err = cfg.Section("").Key("INT64").Int64()
233 v, err = cfg.Section("").Key("UINT").Uint()
234 v, err = cfg.Section("").Key("UINT64").Uint64()
235 v, err = cfg.Section("").Key("TIME").TimeFormat(time.RFC3339)
236 v, err = cfg.Section("").Key("TIME").Time() // RFC3339
238 v = cfg.Section("").Key("BOOL").MustBool()
239 v = cfg.Section("").Key("FLOAT64").MustFloat64()
240 v = cfg.Section("").Key("INT").MustInt()
241 v = cfg.Section("").Key("INT64").MustInt64()
242 v = cfg.Section("").Key("UINT").MustUint()
243 v = cfg.Section("").Key("UINT64").MustUint64()
244 v = cfg.Section("").Key("TIME").MustTimeFormat(time.RFC3339)
245 v = cfg.Section("").Key("TIME").MustTime() // RFC3339
247 // 由 Must 开头的方法名允许接收一个相同类型的参数来作为默认值,
248 // 当键不存在或者转换失败时,则会直接返回该默认值。
249 // 但是,MustString 方法必须传递一个默认值。
251 v = cfg.Seciont("").Key("String").MustString("default")
252 v = cfg.Section("").Key("BOOL").MustBool(true)
253 v = cfg.Section("").Key("FLOAT64").MustFloat64(1.25)
254 v = cfg.Section("").Key("INT").MustInt(10)
255 v = cfg.Section("").Key("INT64").MustInt64(99)
256 v = cfg.Section("").Key("UINT").MustUint(3)
257 v = cfg.Section("").Key("UINT64").MustUint64(6)
258 v = cfg.Section("").Key("TIME").MustTimeFormat(time.RFC3339, time.Now())
259 v = cfg.Section("").Key("TIME").MustTime(time.Now()) // RFC3339
266 ADDRESS = """404 road,
267 NotFound, State, 5000
274 cfg.Section("advance").Key("ADDRESS").String()
278 NotFound, State, 5000
283 赞爆了!那要是我属于一行的内容写不下想要写到第二行怎么办?
287 two_lines = how about \
298 cfg.Section("advance").Key("two_lines").String() // how about continuation lines?
299 cfg.Section("advance").Key("lots_of_lines").String() // 1 2 3 4
302 可是我有时候觉得两行连在一起特别没劲,怎么才能不自动连接两行呢?
305 cfg, err := ini.LoadSources(ini.LoadOptions{
306 IgnoreContinuation: true,
312 需要注意的是,值两侧的单引号会被自动剔除:
315 foo = "some value" // foo: some value
316 bar = 'some value' // bar: some value
326 v = cfg.Section("").Key("STRING").In("default", []string{"str", "arr", "types"})
327 v = cfg.Section("").Key("FLOAT64").InFloat64(1.1, []float64{1.25, 2.5, 3.75})
328 v = cfg.Section("").Key("INT").InInt(5, []int{10, 20, 30})
329 v = cfg.Section("").Key("INT64").InInt64(10, []int64{10, 20, 30})
330 v = cfg.Section("").Key("UINT").InUint(4, []int{3, 6, 9})
331 v = cfg.Section("").Key("UINT64").InUint64(8, []int64{3, 6, 9})
332 v = cfg.Section("").Key("TIME").InTimeFormat(time.RFC3339, time.Now(), []time.Time{time1, time2, time3})
333 v = cfg.Section("").Key("TIME").InTime(time.Now(), []time.Time{time1, time2, time3}) // RFC3339
336 如果获取到的值不是候选值的任意一个,则会返回默认值,而默认值不需要是候选值中的一员。
341 vals = cfg.Section("").Key("FLOAT64").RangeFloat64(0.0, 1.1, 2.2)
342 vals = cfg.Section("").Key("INT").RangeInt(0, 10, 20)
343 vals = cfg.Section("").Key("INT64").RangeInt64(0, 10, 20)
344 vals = cfg.Section("").Key("UINT").RangeUint(0, 3, 9)
345 vals = cfg.Section("").Key("UINT64").RangeUint64(0, 3, 9)
346 vals = cfg.Section("").Key("TIME").RangeTimeFormat(time.RFC3339, time.Now(), minTime, maxTime)
347 vals = cfg.Section("").Key("TIME").RangeTime(time.Now(), minTime, maxTime) // RFC3339
350 ##### 自动分割键值到切片(slice)
355 // Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4]
356 // Input: how, 2.2, are, you -> [0.0 2.2 0.0 0.0]
357 vals = cfg.Section("").Key("STRINGS").Strings(",")
358 vals = cfg.Section("").Key("FLOAT64S").Float64s(",")
359 vals = cfg.Section("").Key("INTS").Ints(",")
360 vals = cfg.Section("").Key("INT64S").Int64s(",")
361 vals = cfg.Section("").Key("UINTS").Uints(",")
362 vals = cfg.Section("").Key("UINT64S").Uint64s(",")
363 vals = cfg.Section("").Key("TIMES").Times(",")
369 // Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4]
370 // Input: how, 2.2, are, you -> [2.2]
371 vals = cfg.Section("").Key("FLOAT64S").ValidFloat64s(",")
372 vals = cfg.Section("").Key("INTS").ValidInts(",")
373 vals = cfg.Section("").Key("INT64S").ValidInt64s(",")
374 vals = cfg.Section("").Key("UINTS").ValidUints(",")
375 vals = cfg.Section("").Key("UINT64S").ValidUint64s(",")
376 vals = cfg.Section("").Key("TIMES").ValidTimes(",")
382 // Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4]
383 // Input: how, 2.2, are, you -> error
384 vals = cfg.Section("").Key("FLOAT64S").StrictFloat64s(",")
385 vals = cfg.Section("").Key("INTS").StrictInts(",")
386 vals = cfg.Section("").Key("INT64S").StrictInt64s(",")
387 vals = cfg.Section("").Key("UINTS").StrictUints(",")
388 vals = cfg.Section("").Key("UINT64S").StrictUint64s(",")
389 vals = cfg.Section("").Key("TIMES").StrictTimes(",")
400 err = cfg.SaveTo("my.ini")
401 err = cfg.SaveToIndent("my.ini", "\t")
404 另一个比较高级的做法是写入到任何实现 `io.Writer` 接口的对象中:
409 cfg.WriteToIndent(writer, "\t")
412 默认情况下,空格将被用于对齐键值之间的等号以美化输出结果,以下代码可以禁用该功能:
415 ini.PrettyFormat = false
422 在获取所有键值的过程中,特殊语法 `%(<name>)s` 会被应用,其中 `<name>` 可以是相同分区或者默认分区下的键名。字符串 `%(<name>)s` 会被相应的键值所替代,如果指定的键不存在,则会用空字符串替代。您可以最多使用 99 层的递归嵌套。
429 GITHUB = https://github.com/%(NAME)s
432 FULL_NAME = github.com/go-ini/%(NAME)s
436 cfg.Section("author").Key("GITHUB").String() // https://github.com/Unknwon
437 cfg.Section("package").Key("FULL_NAME").String() // github.com/go-ini/ini
442 您可以在分区名称中使用 `.` 来表示两个或多个分区之间的父子关系。如果某个键在子分区中不存在,则会去它的父分区中再次寻找,直到没有父分区为止。
447 IMPORT_PATH = gopkg.in/%(NAME)s.%(VERSION)s
450 CLONE_URL = https://%(IMPORT_PATH)s
456 cfg.Section("package.sub").Key("CLONE_URL").String() // https://gopkg.in/ini.v1
462 cfg.Section("package.sub").ParentKeys() // ["CLONE_URL"]
467 如果遇到一些比较特殊的分区,它们不包含常见的键值对,而是没有固定格式的纯文本,则可以使用 `LoadOptions.UnparsableSections` 进行处理:
470 cfg, err := LoadSources(LoadOptions{UnparseableSections: []string{"COMMENTS"}}, `[COMMENTS]
471 <1><L.Slide#2> This slide has the fuel listed in the wrong units <e.1>`))
473 body := cfg.Section("COMMENTS").Body()
476 <1><L.Slide#2> This slide has the fuel listed in the wrong units <e.1>
482 如果数据源中的键名为 `-`,则认为该键使用了自增键名的特殊语法。计数器从 1 开始,并且分区之间是相互独立的。
486 -: Support read/write comments of keys and sections
487 -: Support auto-increment of key names
488 -: Support load multiple files to overwrite key values
492 cfg.Section("features").KeyStrings() // []{"#1", "#2", "#3"}
497 想要使用更加面向对象的方式玩转 INI 吗?好主意。
503 Born = 1993-01-01T20:17:05Z
506 Content = Hi is a good man!
507 Cities = HangZhou, Boston
522 Created time.Time `ini:"-"`
526 cfg, err := ini.Load("path/to/ini")
533 err = ini.MapTo(p, "path/to/ini")
538 err = cfg.Section("Note").MapTo(n)
543 结构的字段怎么设置默认值呢?很简单,只要在映射之前对指定字段进行赋值就可以了。如果键未找到或者类型错误,该值不会发生改变。
553 这样玩 INI 真的好酷啊!然而,如果不能还给我原来的配置文件,有什么卵用?
560 type Embeded struct {
561 Dates []time.Time `delim:"|"`
562 Places []string `ini:"places,omitempty"`
563 None []int `ini:",omitempty"`
567 Name string `ini:"NAME"`
571 NeverMind string `ini:"-"`
576 a := &Author{"Unknwon", true, 21, 2.8, "",
578 []time.Time{time.Now(), time.Now()},
579 []string{"HangZhou", "Boston"},
583 err = ini.ReflectFrom(cfg, a)
597 Dates = 2015-08-07T22:14:22+08:00|2015-08-07T22:14:22+08:00
598 places = HangZhou,Boston
601 #### 名称映射器(Name Mapper)
603 为了节省您的时间并简化代码,本库支持类型为 [`NameMapper`](https://gowalker.org/gopkg.in/ini.v1#NameMapper) 的名称映射器,该映射器负责结构字段名与分区名和键名之间的映射。
607 - `AllCapsUnderscore`:该映射器将字段名转换至格式 `ALL_CAPS_UNDERSCORE` 后再去匹配分区名和键名。
608 - `TitleUnderscore`:该映射器将字段名转换至格式 `title_underscore` 后再去匹配分区名和键名。
618 err = ini.MapToWithMapper(&Info{}, ini.TitleUnderscore, []byte("package_name=ini"))
621 cfg, err := ini.Load([]byte("PACKAGE_NAME=ini"))
624 cfg.NameMapper = ini.AllCapsUnderscore
625 err = cfg.MapTo(info)
630 使用函数 `ini.ReflectFromWithMapper` 时也可应用相同的规则。
632 #### 值映射器(Value Mapper)
634 值映射器允许使用一个自定义函数自动展开值的具体内容,例如:运行时获取环境变量:
638 Foo string `ini:"foo"`
642 cfg, err := ini.Load([]byte("[env]\nfoo = ${MY_VAR}\n")
643 cfg.ValueMapper = os.ExpandEnv
646 err = cfg.Section("env").MapTo(env)
650 本例中,`env.Foo` 将会是运行时所获取到环境变量 `MY_VAR` 的值。
654 任何嵌入的结构都会被默认认作一个不同的分区,并且不会自动产生所谓的父子分区关联:
684 很好,但是,我就是要嵌入结构也在同一个分区。好吧,你爹是李刚!
714 - [API 文档](https://gowalker.org/gopkg.in/ini.v1)
715 - [创建工单](https://github.com/go-ini/ini/issues/new)
719 ### 字段 `BlockMode` 是什么?
721 默认情况下,本库会在您进行读写操作时采用锁机制来确保数据时间。但在某些情况下,您非常确定只进行读操作。此时,您可以通过设置 `cfg.BlockMode = false` 来将读操作提升大约 **50-70%** 的性能。
723 ### 为什么要写另一个 INI 解析库?
725 许多人都在使用我的 [goconfig](https://github.com/Unknwon/goconfig) 来完成对 INI 文件的操作,但我希望使用更加 Go 风格的代码。并且当您设置 `cfg.BlockMode = false` 时,会有大约 **10-30%** 的性能提升。
727 为了做出这些改变,我必须对 API 进行破坏,所以新开一个仓库是最安全的做法。除此之外,本库直接使用 `gopkg.in` 来进行版本化发布。(其实真相是导入路径更短了)