使用 INI 格式文件作为配置,配置数据的加载,管理,使用。
如果你想要更多文件内容格式的支持,推荐使用 gookit/config
go get github.com/gookit/ini/v2
示例数据(testdata/test.ini):
# comments
name = inhere
age = 50
debug = true
hasQuota1 = 'this is val'
hasQuota2 = "this is val1"
can2arr = val0,val1,val2
shell = ${SHELL}
noEnv = ${NotExist|defValue}
nkey = val in default section
; comments
[sec1]
key = val0
some = value
stuff = things
varRef = %(nkey)s
package main
import (
"github.com/gookit/ini/v2"
)
// go run ./examples/demo.go
func main() {
// err := ini.LoadFiles("testdata/tesdt.ini")
// LoadExists 将忽略不存在的文件
err := ini.LoadExists("testdata/test.ini", "not-exist.ini")
if err != nil {
panic(err)
}
// 加载更多,相同的键覆盖之前数据
err = ini.LoadStrings(`
age = 100
[sec1]
newK = newVal
some = change val
`)
// fmt.Printf("%v\n", ini.Data())
}
获取整型
age := ini.Int("age")
fmt.Print(age) // 100
获取布尔值
val := ini.Bool("debug")
fmt.Print(val) // true
获取字符串
name := ini.String("name")
fmt.Print(name) // inhere
获取section数据(string map)
val := ini.StringMap("sec1")
fmt.Println(val)
// map[string]string{"key":"val0", "some":"change val", "stuff":"things", "newK":"newVal"}
获取的值是环境变量
value := ini.String("shell")
fmt.Printf("%q", value) // "/bin/zsh"
通过key path来直接获取子级值
value := ini.String("sec1.key")
fmt.Print(value) // val0
支持变量参考
value := ini.String("sec1.varRef")
fmt.Printf("%q", value) // "val in default section"
设置新的值
// set value
ini.Set("name", "new name")
name = ini.String("name")
fmt.Printf("%q", value) // "new name"
type User struct {
Name string
Age int
}
user := &User{}
ini.MapStruct(ini.DefSection(), user)
dump.P(user)
[portal]
url = http://%(host)s:%(port)s/Portal
host = localhost
port = 8080
启用变量解析后,将会解析这里的 %(host)s 并替换为相应的变量值 localhost:
cfg := ini.New()
// 启用变量解析
cfg.WithOptions(ini.ParseVar)
fmt.Print(cfg.String("portal.url"))
// OUT:
// http://localhost:8080/Portal
type Options struct {
// 设置为只读模式. default False
Readonly bool
// 解析 ENV 变量名称. default True
ParseEnv bool
// 解析变量引用 "%(varName)s". default False
ParseVar bool
// 变量左侧字符. default "%("
VarOpen string
// 变量右侧字符. default ")s"
VarClose string
// 忽略键名称大小写. default False
IgnoreCase bool
// 默认的section名称. default "__default"
DefSection string
// 路径分隔符,当通过key获取子级值时. default ".", 例如 "section.subKey"
SectionSep string
}
cfg := ini.New()
cfg.WithOptions(ini.ParseEnv,ini.ParseVar, func (opts *Options) {
opts.SectionSep = ":"
opts.DefSection = "default"
})
github 地址:https://github.com/gookit/ini

