H5W3
当前位置:H5W3 > go > 正文

【go】golang 多级toml解析

因为在开发中使用toml进行配置,并使用了 viper 这多功能解析库来解析 toml配置文件。遇到 编组失败

如 配置文件:

[database]
[database.db1]
[database.db1.dev]
driver = "mysql"
dsn = "cusr:[email protected](192.168.6.182:3306)/hue?charset=utf8mb4&parseTime=true"
maxOpenConns = 1000
maxIdleConns = 200
connMaxLifeTime = 50
[database.db1.pro]
driver = "mysql"
dsn = "cusr:[email protected](192.168.6.182:3306)/hue?charset=utf8mb4&parseTime=true"
maxOpenConns = 1000
maxIdleConns = 200
connMaxLifeTime = 50
[database.db1.test]
driver = "mysql"
dsn = "cusr:[email protected](192.168.6.182:3306)/hue?charset=utf8mb4&parseTime=true"
maxOpenConns = 1000
maxIdleConns = 200
connMaxLifeTime = 50
[database.db2]
[database.db2.dev]
driver = "mysql"
dsn = "cusr:[email protected](192.168.6.182:3306)/hue?charset=utf8mb4&parseTime=true"
maxOpenConns = 1000
maxIdleConns = 200
connMaxLifeTime = 50
[database.db2.dev]
driver = "mysql"
dsn = "cusr:[email protected](192.168.6.182:3306)/hue?charset=utf8mb4&parseTime=true"
maxOpenConns = 1000
maxIdleConns = 200
connMaxLifeTime = 50
[database.db3]
[database.db3.dev]
driver = "mysql"
dsn = "cusr:[email protected](192.168.6.182:3306)/hue?charset=utf8mb4&parseTime=true"
maxOpenConns = 1000
maxIdleConns = 200
connMaxLifeTime = 50
# and more 后面还有 db4 db5 db6 。。。。

使用 golang进行 解析:

type singleConf struct {
driver          string `toml:"driver"`
dsn             string `toml:"dsn"`
maxOpenConns    int    `toml:"maxOpenConns"`
maxIdleConns    int    `toml:"maxIdleConns"`
connMaxLifeTime int    `toml:"connMaxLifeTime"`
}
type envConf struct {
dev singleConf
pro singleConf
test singleConf
}
type tomlConf struct {
database map[string]envConf
}
var TomlConf tomlConf
func init() {
confDir, _ := filepath.Abs(path.Dir("."))
confDir = confDir + "/conf/"
fmt.Println(confDir)
viper.AddConfigPath(confDir)
viper.SetConfigType("toml")
viper.SetConfigName("db")
if err := viper.ReadInConfig(); err != nil {
panic(err)
}
if err := viper.Unmarshal(&TomlConf); err != nil {
panic(err)
}
fmt.Println(TomlConf.database)
}

打印之后 是 一个空的 map

viper是你用的库?一般通过反射的接口都需要把字段设置为“导出的”。你的database未导出,把配置相关结构里面的字段都改成首字母大写吧。例如:database -> Database

回答

本文地址:H5W3 » 【go】golang 多级toml解析

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址