在 ini 文件中,每个键值对占用一行,中间使用=隔开。以#开头的内容为注释。ini 文件是以分区(section)组织的。
分区以[name]开始,在下一个分区前结束。所有分区前的内容属于默认分区,如my.ini文件中的app_name
vim /root/.my.cnf
app_name=lys_app
[client]
host=10.6.8.238
port=3306
user=user0001
password=User0001!
[slave]
host=10.6.8.238
port=23306
user=root
password=mysql
package collector
import (
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"gopkg.in/ini.v1"
)
// 包 ini 在 Go 中提供 INI 文件读取和写入功能。
func TestIni(t *testing.T) {
var configMycnf = "/root/.my.cnf"
opts := ini.LoadOptions{
// MySQL ini file can have boolean keys.
AllowBooleanKeys: true,
}
cfg, err1 := ini.LoadSources(opts, configMycnf)
if err1 == nil {
fmt.Printf("slave含有host:%v \n", cfg.Section("slave").Key("host").String())
fmt.Printf("slave含有port:%v \n", cfg.Section("slave").Key("port").MustInt())
fmt.Printf("slave含有user:%v \n", cfg.Section("slave").Key("user").String())
fmt.Printf("slave含有password:%v \n", cfg.Section("slave").Key("password").String())
// 新增并保存
cfg.Section("new_section").Key("new_key").SetValue("new_key_value")
cfg.SaveTo("/root/lys.cnf")
}
// 获取要删除的参数所在的 Section
section, err := cfg.GetSection("your_section_name")
if err != nil {
log.Fatal(err)
}
// 删除参数
err = section.DeleteKey("parameter_to_delete")
if err != nil {
log.Fatal(err)
}
}
[root@lys-mysql ~]# cat lys.cnf
app_name=lys_app
[client]
host = 10.6.8.238
port = 3306
user = user0001
password = User0001!
[slave]
host = 10.6.8.238
port = 23306
user = root
password = mysql
[new_section]
new_key = new_key_value
// 遍历各个 section 和 key,并修改值
for _, section := range cfg.Sections() {
for _, key := range section.Keys() {
// 获取原始值
oldValue := key.String()
newValue := oldValue
if strings.ContainsAny(oldValue, ",%/*abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") {
fmt.Println("String contains ',' or '%'")
// 做一些修改(这里示例是在值两侧添加引号)
newValue = "'" + oldValue + "'"
}
// 设置新值
key.SetValue(newValue)
}
}
https://ini.unknwon.io/docs/intro/getting_started