介绍
GO-INI是最流行 的 Go 语言 操作库,在go语言的地位相当于Java的yml,yaml。
INI 是为 Go 而生的。一方面,它可以直接使用Go语言的相关数据结构并自动转换。另一方面,它兼容多种格式并且高度可定制。
在实际开发中,配置信息一般不会硬编码在代码中,而是通常放在配置文件中,或者放在数据库或缓存中。今天介绍的go-ini是一个读写ini文件的库。 GO-INI是go的专属配置文件。配置文件格式有很多种,常用的有json、xml、ini。其中ini由section和key组成。
基本语法
INI 文件是一种基于文件的文件格式,由一系列部分和键值对组成。
节用[]
括起来。
一个section代表一组相关的键值对,可以是任何合法的文本。
键和值用=
连接
key=value
键和值不包含等号,方括号,分号,如果字符需要用转义字符\
转义。
注释为;
和#
;注释
#注释
基本使用
- 下载
go get gopkg.in/ini.v1
并新建目录
//go-ini的不同下载源
go get github.com/go-ini/ini
go get gopkg.in/ini.v1
- 引入ini
import (
"fmt"
"gopkg.in/ini.v1"
)
文件读取的方法需要从根目录开始。
- 加载ini文件对象
inifile, err := ini.Load("ini/my.ini")
if err != nil {
panic(err)
}
ini文件可以在任何目录下,主要在加载时正确写入路径即可。
ini.Load()
参数默认从根目录开始。
- 通过对象方法操作ini文件
# ini文件
# possible values : production,development
app_mode = development
[path]
# Path to where grafana can store temp files
data = /github/com/go-ini/ini
[server]
# Protocol (http or https)
protocol = http
# The http port to use
http_port = 80
# develop environment
env = true
//分区读取,默认分区用空字符串表示
app_mode := inifile.Section("").Key("app_mode").String()
fmt.Println(app_mode)
//读取指定分区
path := inifile.Section("path").Key("data").String()
fmt.Println(path)
//读取时附加限制操作
protocol := inifile.Section("server").Key("protocol").In("http", []string{
"http", "https"})
fmt.Println(protocol)
//自动类型转换(ini加载的都是字符串转换为go内置数据类型)
port := inifile.Section("server").Key("http_port").MustInt(8080)
what := inifile.Section("server").Key("env").MustBool(false)
fmt.Printf("port type %T,port value%v", port, port)
fmt.Printf("env type %T, env value %v", what, what)
更多移步官方网站INI
. . .
相关推荐
热门推荐
特别练习-12 性格测试-01
30天前
C++代码中边界效应引发的问题
26天前
ch3_5多进程中的地址映射
26天前
如何在浏览器中下载网站的https证书
26天前
无心剑英译朱熹《观书有感二首·其一》
26天前
ads via 小工具