读取的文件
vim /root/.my.cnf
[client]
host = 10.6.8.238
port = 3306
user = root
password = mysql
[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")
}
}
输出的文件
[root@lys-mysql ~]# cat lys.cnf
[client]
host = 10.6.8.238
port = 3306
user = root
password = mysql
[slave]
host = 10.6.8.238
port = 23306
user = root
password = mysql
[new_section]
new_key = new_key_value