TOML 的全稱是 Tom's Obvious, Minimal Language,因為它的作者是 GitHub 聯合創始人 Tom Preston-Werner。
TOML 的目標是成為一個極簡的配置文件格式。TOML 被設計成可以無歧義地被映射為哈希表,從而被多種語言解析。
TOML 的Spec https://github.com/toml-lang/toml
中文版: http://segmentfault.com/a/1190000000477752
Golang的解析庫很多:
- Go (@thompelletier) - https://github.com/pelletier/go-toml
- Go (@laurent22) - https://github.com/laurent22/toml-go
- Go w/ Reflection (@BurntSushi) - https://github.com/BurntSushi/toml
- Go (@achun) - https://github.com/achun/tom-toml
- Go (@naoina) - https://github.com/naoina/toml
對比后,推薦:https://github.com/BurntSushi/toml
更新是16天前的,而且支持把配置文件反序列化成類對象,把類對象序列號成配置文件。而且關注的人也多。
下面是 https://github.com/BurntSushi/toml 的例子翻譯:
比如下面的配置文件:
Age = 25 Cats = [ "Cauchy", "Plato" ] Pi = 3.14 Perfection = [ 6, 28, 496, 8128 ] DOB = 1987-07-05T05:45:00Z
對應的Go類如下:
type Config struct {
Age int
Cats []string
Pi float64
Perfection []int
DOB time.Time // requires `import time`
}
讀取配置文件的代碼如下:
var conf Config
if _, err := toml.Decode(tomlData, &conf); err != nil {
// handle error
} 如果我們配置文件中字段名和類的名稱無法映射,則可以使用 struct tags
比如,配置文件為:
some_key_NAME = "wat"
對應的Go類如下:
type TOML struct {
ObscureKey string `toml:"some_key_NAME"`
}
下面是一個例子,自動把duration 字符串解析成 time.Duration 對象
配置文件:
[[song]] name = "Thunder Road" duration = "4m49s" [[song]] name = "Stairway to Heaven" duration = "8m03s"
對應Go類如下:
type song struct {
Name string
Duration duration
}
type songs struct {
Song []song
}
var favorites songs
if _, err := toml.Decode(blob, &favorites); err != nil {
log.Fatal(err)
}
for _, s := range favorites.Song {
fmt.Printf("%s (%s)\n", s.Name, s.Duration)
}
這里我們需要 讓duration 類型滿足 encoding.TextUnmarshaler 接口
type duration struct {
time.Duration
}
func (d *duration) UnmarshalText(text []byte) error {
var err error
d.Duration, err = time.ParseDuration(string(text))
return err
}
對於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" ]
對應的Go類如下:
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
}
注意,這里是不區分大小寫的匹配。
