我们常见的一些配置文件包括,yaml、xml、toml、json和ini。
今天我们就来介绍这个toml配置文件,在go语言中的使用。
注:我选择toml的原因是toml配置简单,注释方便,读取方便。
包介绍
toml(Tom’s Obvious, Minimal Language),简约又明显的语言。
使用的包是
github.com/BurntSushi/toml
安装该包
go get github.com/BurntSushi/toml@latest
使用列子
我们一般将配置文件中的字段映射到结构体中,这也方便了使用者的使用过程。
-
简单例子
test.toml文件
Name = "张三" Age = 18 Money = 1.2 Hobby = ["打游戏","去医院疗伤"] Birthday = 2023-01-05
toml_test.go
package test import ( "fmt" "github.com/BurntSushi/toml" "os" "testing" "time" ) type Config struct { Name string Age int Money float64 Hobby []string Birthday time.Time } func TestToml1(t *testing.T) { f := "../conf/test.toml" if _, err := os.Stat(f); err != nil { panic(err) } var conf Config if _, err := toml.DecodeFile(f, &conf); err != nil { panic(err) } fmt.Printf("Name: %v\n", conf.Name) fmt.Printf("Age: %v\n", conf.Age) fmt.Printf("Money: %v\n\r", conf.Money) fmt.Printf("Hobby: %v\n\r", conf.Hobby) fmt.Printf("Birthday: %v\n\r", conf.Birthday) }
输出
Name: 张三
Age: 18
Money: 1.2
Hobby: [打游戏 去医院疗伤]
Birthday: 2023-01-05 00:00:00 +0800 CST -
对象数组
test.toml
distros = [ {name = "Arch Linux", packages = "pacman"}, {name = "Void Linux", packages = "xbps"}, {name = "Debian", packages = "apt"}, ]
toml_test.go
package test import ( "fmt" "github.com/BurntSushi/toml" "os" "testing" "time" ) type ( example struct { Distros []distro } distro struct { Name string Pkg string `toml:"Packages"` } ) var f = "../conf/test.toml" // 对象数组 func TestToml2(t *testing.T) { if _, err := os.Stat(f); err != nil { panic(err) } var conf example if _, err := toml.DecodeFile(f, &conf); err != nil { panic(err) } fmt.Println(conf) }
-
map映射
test.toml
## test1 #Name = "张三" #Age = 18 #Money = 1.2 #Hobby = ["打游戏","去医院疗伤"] #Birthday = 2023-01-05 #test2 distros = [ {name = "Arch Linux", packages = "pacman"}, {name = "Void Linux", packages = "xbps"}, {name = "Debian", packages = "apt"}, ] [[characters.star-trek]] name = "James Kirk" rank = "Captain" [[characters.star-trek]] name = "Spock" rank = "Science officer"
toml_test.go
package test import ( "fmt" "github.com/BurntSushi/toml" "os" "testing" "time" ) type ( example struct { Distros []distro Characters map[string][]struct { Name string Rank string } } distro struct { Name string Pkg string `toml:"Packages"` } ) var f = "../conf/test.toml" // map映射 func TestToml3(t *testing.T) { if _, err := os.Stat(f); err != nil { panic(err) } var conf example if _, err := toml.DecodeFile(f, &conf); err != nil { panic(err) } fmt.Println(conf) }
结语
想要了解更多请点击:go-pkg toml文章来源:https://www.toymoban.com/news/detail-652114.html
参考资料:BurntSushi/toml: TOML parser for Golang with reflection. (github.com)文章来源地址https://www.toymoban.com/news/detail-652114.html
到了这里,关于Go --- toml配置文件使用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!