BoyChai's Blog - INI https://blog.boychai.xyz/index.php/tag/INI/ [Go]读取INI配置文件 https://blog.boychai.xyz/index.php/archives/43/ 2022-12-12T15:03:00+00:00 INIINI文件是Initialization File的缩写,意思为"配置文件;初始化文件;",以节(section)和键(key)构成,常用于微软Windows操作系统中。这种配置文件的文件扩展名多为INI,故名。环境在主程序文件目录下创建"my.ini"文件内容如下app_mode = development [paths] data = /home/git/grafana [server] protocol = http http_port = 9999 enforce_domain = true开始使用package main import ( "fmt" "github.com/go-ini/ini" ) func main() { // 读取配置文件 cfg, err := ini.Load("my.ini") if err != nil { panic(err) } //读取 //读取app_mode fmt.Println("app_mode:", cfg.Section("").Key("app_mode")) //读取paths.data fmt.Println("paths.data:", cfg.Section("paths").Key("data").String()) //读取server.protocol并限制值 //如果没有值或值错误则使用"http" fmt.Println("server.protocol:", cfg.Section("server").Key("protocol").In("http", []string{"http", "https"})) //读取时进行类型转换,MustInt()可以存放默认值,如果转换失败则使用里面的值 fmt.Printf("Port Number: (%[1]T) %[1]d\n", cfg.Section("server").Key("http_port").MustInt()) //修改 //修改app_mode的值为production cfg.Section("").Key("app_mode").SetValue("production") //修改完毕写入"my.ini.local"文件 cfg.SaveTo("my.ini.local") }