一、简介
配置文件有很多种类,比如.ini、xml、json、YAML再到TOML,TOML 的全称是 Tom's Obvious, Minimal Language,因为它的作者是 GitHub 联合创始人 Tom Preston-Werner。TOML 的目标是成为一个极简的配置文件格式。TOML 被设计成可以无歧义地被映射为哈希表,从而被多种语言解析。
说白了,就是将指定格式的配置文件中的内容,映射到某个变量中,从而通过这个变量取访问配置文件中的内容。
关于TOML的一些规范
1、OML是大小写敏感的
2、TOML文件必须是UTF8编码的
3、空白符可以是制表符(0x09)或空格(0x20)
4、换行符可以是 LF (0x0A) 或 CRLF (0x0D0A)
在最开始接触go语言的时候,配置文件,我往往都是通过json.Unmarshal进行关联映射。如下:
假设配置文件如下:{
"debug": true,
"db": {
"dsn": "root:test@tcp(127.0.0.1:3363)/findme",
"maxIdle": 30
}
}
先来搞一下,如果不其他组件,我们需要自己读取配置文件,通过json.Unmarshal进行关联映射。如下:
config/conf.gopackage config
import (
"log"
"encoding/json"
"github.com/toolkits/file"
)
type GlobalConfig struct {
Debug bool `json:"debug"`
DataBase DataBase `json:"db"`
}
type DataBase struct {
DNS string `json:"dsn"`
MaxIdle int `json:"maxIdle"`
}
var gConfig * GlobalConfig
func GetConfig() *GlobalConfig {
return gConfig
}
func ParseConf(filePath string) {
if filePath == "" {
log.Fatalln("use -c to specify configuration file")
}
if !file.IsExist(filePath) {
log.Fatalln("config file:", filePath, "is not existent")
}
fileContent, err :=file.ToString(filePath)
if err != nil {
log.Fatalln("read config file:", filePath, "fail:", err)
}
err = json.Unmarshal([]byte(fileContent), &gConfig)
if err != nil {
log.Fatalln("parse config file:", filePath, "fail:", err)
}
}
调用如下:package main
import (
"fmt"
"flag"
"test/config"
)
func main() {
configFile := flag.String("c", "config/conf.toml", "configuration file")
flag.Parse()
config.ParseConf(*configFile)
fmt.Println(config.GetConfig().DataBase) //打印数据库信息
}
二、案例
如果我们需要使用的配置文件,还是上面内容,此时,需要我们将其转为toml格式的,如下:#是否开启调试模式
debug = true
#数据库的配置
[db]
dns = "root:test@tcp(127.0.0.1:3363)/findme"
maxIdle = 30
映射配置文件的程序如下:package config
import (
"log"
"github.com/BurntSushi/toml"
"sync"
)
var lock = new(sync.RWMutex)
type GlobalConfig struct {
Debug bool `toml:"debug"`
DataBase DataBase `toml:"db"`
}
type DataBase struct {
DNS string `toml:"dns"`
MaxIdle int `toml:"maxIdle"`
}
var gConfig *GlobalConfig
func GetConfig() *GlobalConfig {
lock.RLock() //加读锁,防止读的时候,被写
defer lock.RUnlock() //读完解锁
return gConfig
}
func ParseConf(filePath string) {
lock.RLock()
defer lock.RUnlock()
if filePath == "" {
log.Fatalln("use -c to specify configuration file")
}
_, err := toml.DecodeFile(filePath, &gConfig)
if err != nil {
log.Println("toml.DecodeFile error")
panic(err)
}
}
调用和上面保持一致即可,运行结果如下:{root:test@tcp(127.0.0.1:3363)/findme 30}
注意事项:若配置文件是json格式,我们在结构体的tags中使用了json,配置文件是toml格式的,我们在结构体的tags中使用了toml。