通过反射的Go的TOML解析器和编码器
TOML全称为Tom’s Obvious,Minimal Language。 这个Go包提供了一个类似于Go的标准库json和xml包的反射界面。 此包还支持encoding.TextUnmarshaler和encoding.TextMarshaler接口,以便自定义数据表示。
示例1
package main
import (
"github.com/BurntSushi/toml"
"log"
)
type songInfo struct {
Name string
Duration int
}
type mysqlInfo struct {
Host string
PassWord string
}
type config struct {
Bc string
Song songInfo
Mysql mysqlInfo
}
func test_toml() {
var cg config
var cpath string = "./example.toml"
if _, err := toml.DecodeFile(cpath, &cg); err != nil {
log.Fatal(err)
}
log.Println("%v %v %v\n", cg.Bc, cg.Song.Name,cg.Mysql.PassWord)
}
func main() {
test_toml()
}
结构体中变量注意要首字母要大写
toml文件
Bc = "坐标北京"
[song]
Name = "北京.北京"
Duration = 900
[mysql]
Host = "localhost"
PassWord = "123456"
示例2
package main
import (
"fmt"
"time"
"github.com/BurntSushi/toml"
)
type tomlConfig struct {
Title string
Owner ownerInfo
DB database `toml:"database"`
Servers map[string]server
Clients clients
}
type ownerInfo struct {
Name string
Org string `toml:"organization"`
Bio string
DOB time.Time
}
type database struct {
Server string
Ports []int
ConnMax int `toml:"connection_max"`
Enabled bool
}
type server struct {
IP string
DC string
}
type clients struct {
Data [][]interface{}
Hosts []string
}
func main() {
var config tomlConfig
if _, err := toml.DecodeFile("/home/wilson/gocode/src/webservice01/etcddemo01/describe.toml", &config); err != nil {
fmt.Println(err)
return
}
fmt.Printf("Title: %s\n", config.Title)
fmt.Printf("Owner: %s (%s, %s), Born: %s\n",
config.Owner.Name, config.Owner.Org, config.Owner.Bio,
config.Owner.DOB)
fmt.Printf("Database: %s %v (Max conn. %d), Enabled? %v\n",
config.DB.Server, config.DB.Ports, config.DB.ConnMax,
config.DB.Enabled)
for serverName, server := range config.Servers {
fmt.Printf("Server: %s (%s, %s)\n", serverName, server.IP, server.DC)
}
fmt.Printf("Client data: %v\n", config.Clients.Data)
fmt.Printf("Client hosts: %v\n", config.Clients.Hosts)
}
对应的toml文件
# This is a TOML document. Boom.
title = "TOML Example"
[owner]
name = "Tom Preston-Werner"
organization = "GitHub"
bio = "GitHub Cofounder & CEO\nLikes tater tots and beer."
dob = 1979-05-27T07:32:00Z # First class dates? Why not?
[database]
server = "192.168.1.1"
ports = [ 8001, 8001, 8002 ]
connection_max = 5000
enabled = true
[servers]
# You can indent as you please. Tabs or spaces. TOML don't care.
[servers.alpha]
ip = "10.0.0.1"
dc = "eqdc10"
[servers.beta]
ip = "10.0.0.2"
dc = "eqdc10"
[clients]
data = [ ["gamma", "delta"], [1, 2] ] # just an update to make sure parsers support it
# Line breaks are OK when inside arrays
hosts = [
"alpha",
"omega"
]