0 需求分析
- go语言读取ini的配置文件
- 获取指定分区的对象或名称
- 获取指定分区下的所有对象或名称
- 自动类型转换(读取的3306直接为int类型)
- 结构体映射,通过结构体直接访问配置文件信息
参考链接:
https://blog.csdn.net/Guzarish/article/details/118626693?spm=1001.2101.3001.4242.2&utm_relevant_index=4
标题1 环境搭建
首先,安装go-ini的安装包,默认安装到GOPATH中
go get gopkg.in/ini.v1
其次,我们需要在任意目录创建两个文件(my.ini和main.go)
my.ini文件内容如下:
# possible values : production, development
app_mode = development
[paths]
# Path to where grafana can store temp files, sessions, and the sqlite3 db (if that is used)
data = /home/git/grafana
[server]
# Protocol (http or https)
protocol = http
# The http port to use
http_port = 9999
enforce_domain=bool
[mysql]
Sql_port = 3306
USER = root
PASSWORD = root
[ip]
A03=192.168.1.203
A04=192.168.1.204
A05=192.168.1.205
A06=192.168.1.206
2 结果展示
3 源代码
main.go
package main
import (
"fmt"
"os"
"gopkg.in/ini.v1"
)
type sqlStruct struct {
Sql_port int
USER string
PASSWORD string
}
func main() {
//参考网页 go ini的中文解释
//https://blog.csdn.net/Guzarish/article/details/118626693?spm=1001.2101.3001.4242.2&utm_relevant_index=4
cfg, err := ini.Load("my.ini")
if err != nil {
fmt.Printf("Fail to read file: %v", err)
os.Exit(1)
}
// 典型读取操作,默认分区可以使用空字符串表示
fmt.Println("App Mode:", cfg.Section("").Key("app_mode").String())
fmt.Println("Data Path:", cfg.Section("paths").Key("data").String())
fmt.Println("******************************")
// fmt.Println("Data Path:", cfg.Section("paths").KeyStrings()[0])
// fmt.Println("Data Path:", cfg.Section("paths").Keys()[0])
//fmt.Printf("%T\n", cfg.Section("paths").KeyStrings())
// 试一试自动类型转换
fmt.Printf("Port Number: (%[1]T) %[2]d\n", cfg.Section("server").Key("http_port").MustInt(), 23)
fmt.Printf("Enforce Domain: (%[1]T) %[1]v\n", cfg.Section("server").Key("enforce_domain").MustBool())
fmt.Println("******************************")
//获取所有分区对象或名称
values := cfg.Section("ip").Keys()
keys := cfg.Section("ip").KeyStrings()
fmt.Printf("ip keys %v\n", keys)
fmt.Printf("ip values %v\n", values)
fmt.Println("******************************")
//结构体映射
mySql := new(sqlStruct)
err = cfg.Section("mysql").MapTo(mySql)
if err != nil {
return
}
fmt.Printf("mySql.PASSWORD (%[1]T) %[1]v\n", mySql.PASSWORD)
fmt.Printf("mySql.Sql_port (%[1]T) %[1]v\n", mySql.Sql_port)
fmt.Println("******************************")
// // 修改某个值然后进行保存
// cfg.Section("").Key("app_mode").SetValue("production")
// cfg.SaveTo("my.ini.local")
}