和分区一样,您也可以直接获取键而忽略错误处理:
判断某个键是否存在:
yes := cfg.Section("").HasKey("key name")
创建一个新的键:
err := cfg.Section("").NewKey("name", "value")
keys := cfg.Section("").Keys()
names := cfg.Section("").KeyStrings()
获取分区下的所有键值对的克隆:
忽略键名的大小写
有时候分区和键的名称大小写混合非常烦人,这个时候就可以通过 将所有分区和键名在读取里强制转换为小写:
cfg, err := ini.InsensitiveLoad("filename")
//...
// sec1 和 sec2 指向同一个分区对象
sec2, err := cfg.GetSection("SecTIOn")
// key1 和 key2 指向同一个键对象
key1, err := sec1.GetKey("Key")
类似 MySQL 配置中的布尔值键
MySQL 的配置文件中会出现没有具体值的布尔类型的键:
[mysqld]
...
skip-host-cache
skip-name-resolve
cfg, err := ini.LoadSources(ini.LoadOptions{
AllowBooleanKeys: true,
}, "my.cnf")
这些键的值永远为 true
,且在保存到文件时也只会输出键名。
如果您想要通过程序来生成此类键,则可以使用 NewBooleanKey
:
key, err := sec.NewBooleanKey("skip-host-cache")
你是否也曾被下面的配置文件所困扰?
cfg, err := ini.ShadowLoad(".gitconfig")
f.Section(`remote "origin"`).Key("url").String()
// Result: https://github.com/Antergone/test1.git
f.Section(`remote "origin"`).Key("url").ValueWithShadows()
// Result: []string{
// "https://github.com/Antergone/test1.git",
// "https://github.com/Antergone/test2.git",
// }
如果数据源中的键名为 -
,则认为该键使用了自增键名的特殊语法。计数器从 1 开始,并且分区之间是相互独立的。
[features]
-: Support read/write comments of keys and sections
-: Support auto-increment of key names
-: Support load multiple files to overwrite key values