和分区一样,您也可以直接获取键而忽略错误处理:

判断某个键是否存在:

  1. yes := cfg.Section("").HasKey("key name")

创建一个新的键:

  1. err := cfg.Section("").NewKey("name", "value")
  1. keys := cfg.Section("").Keys()
  2. names := cfg.Section("").KeyStrings()

获取分区下的所有键值对的克隆:

忽略键名的大小写

有时候分区和键的名称大小写混合非常烦人,这个时候就可以通过 将所有分区和键名在读取里强制转换为小写:

  1. cfg, err := ini.InsensitiveLoad("filename")
  2. //...
  3. // sec1 和 sec2 指向同一个分区对象
  4. sec2, err := cfg.GetSection("SecTIOn")
  5. // key1 和 key2 指向同一个键对象
  6. key1, err := sec1.GetKey("Key")

类似 MySQL 配置中的布尔值键

MySQL 的配置文件中会出现没有具体值的布尔类型的键:

  1. [mysqld]
  2. ...
  3. skip-host-cache
  4. skip-name-resolve
  1. cfg, err := ini.LoadSources(ini.LoadOptions{
  2. AllowBooleanKeys: true,
  3. }, "my.cnf")

这些键的值永远为 true,且在保存到文件时也只会输出键名。

如果您想要通过程序来生成此类键,则可以使用 NewBooleanKey

  1. key, err := sec.NewBooleanKey("skip-host-cache")

你是否也曾被下面的配置文件所困扰?

  1. cfg, err := ini.ShadowLoad(".gitconfig")
  2. f.Section(`remote "origin"`).Key("url").String()
  3. // Result: https://github.com/Antergone/test1.git
  4. f.Section(`remote "origin"`).Key("url").ValueWithShadows()
  5. // Result: []string{
  6. // "https://github.com/Antergone/test1.git",
  7. // "https://github.com/Antergone/test2.git",
  8. // }

如果数据源中的键名为 -,则认为该键使用了自增键名的特殊语法。计数器从 1 开始,并且分区之间是相互独立的。

  1. [features]
  2. -: Support read/write comments of keys and sections
  3. -: Support auto-increment of key names
  4. -: Support load multiple files to overwrite key values