TOML

TOML 的全称是 Tom’s Obvious, Minimal Language,意为 Tom 的(语义)明显、(配置)最小化的语言。

我们用JSON配置格式与TOML进行类比。

JSON:

1
2
3
4
5
6
7
8
9
10
{
"name": "Orange",
"physical": {
"color": "orange",
"shape": "round"
},
"site": {
"google.com": true
}
}

TOML:

1
2
3
4
name = "Orange"
physical.color = "orange"
physical.shape = "round"
site."google.com" = true

详细的介绍参阅官方文档,此处不再赘述。

GO操作TOML

我们使用BurntSushi的toml库进行TOML配置文件的操作。

使用go Module创建一个测试module

1
$ go mod init github.com/l2m2/go-toml-demo

安装TOML操作库

1
$ go get github.com/BurntSushi/toml

假设我们的配置文件长这样

1
2
3
4
5
Age = 25
Cats = [ "Cauchy", "Plato" ]
Pi = 3.14
Perfection = [ 6, 28, 496, 8128 ]
DOB = 1987-07-05T05:45:00Z

我们需要在Go中定义数据结构如下

1
2
3
4
5
6
7
type Config1 struct {
Age int
Cats []string
Pi float64
Perfection []int
DOB time.Time
}

然后这样解析,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
func decode1() {
ex, err := os.Executable()
if err != nil {
panic(err)
}
exPath := filepath.Dir(ex)
fmt.Println(exPath)
var conf Config1
if _, err := toml.DecodeFile(filepath.Join(exPath, "conf1.toml"), &conf); err != nil {
panic(err)
}
fmt.Printf("%#v", conf)
// main.Config1{Age:25, Cats:[]string{"Cauchy", "Plato"}, Pi:3.14, Perfection:[]int{6, 28, 496, 8128}, DOB:time.Time{wall:0x0, ext:62688059100, loc:(*time.Location)(nil)}}
}

我们也可以对配置文件中的标签和数据结构的名称进行映射

例如,

1
2
3
4
5
6
7
type Config2 struct {
Age int
Cats []string
Pi float64
Perf []int `toml:Perfection` // 打标签
DOB time.Time
}

我们把数据结构中的Perfection替换成了Perf,那么打印出的值也变成了下面这样

1
// main.Config2{Age:25, Cats:[]string{"Cauchy", "Plato"}, Pi:3.14, Perf:[]int(nil), DOB:time.Time{wall:0x0, ext:62688059100, loc:(*time.Location)(nil)}}

改变配置,写入文件

1
2
3
4
5
6
7
conf.Age = 34
fmt.Printf("%#v", conf)
f, _ := os.Create(confPath)
defer f.Close()
if err := toml.NewEncoder(f).Encode(conf); err != nil {
panic(err)
}

完整代码在这里

Reference