Go学习笔记一:解析toml配置文件
生活随笔
收集整理的這篇文章主要介紹了
Go学习笔记一:解析toml配置文件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
本文系作者原創,轉載請注明出處https://www.cnblogs.com/sonofelice/p/9085291.html。
一些mysql或者日志路徑的信息需要放在配置文件中。那么本博文主要介紹go對toml文件的解析。
使用了"github.com/BurntSushi/toml"標準庫。
1 toml文件的寫法
[Mysql] UserName = "sonofelice" Password = "123456" IpHost = "127.0.0.1:8902" DbName = "sonofelice_db"
2 對toml文件的解析
為了要解析上面的toml文件,我們需要定義與之對應的struct:
type Mysql struct {
UserName string
Password string
IpHost string
DbName string
}
那么其實可以寫這樣一個conf.go
package conf
import (
"nlu/log"
"github.com/BurntSushi/toml"
"flag"
)
var (
confPath string
// Conf global
Conf = &Config{}
)
// Config .
type Config struct {
Mysql *Mysql
}
type Mysql struct {
UserName string
Password string
IpHost string
DbName string
}
func init() {
flag.StringVar(&confPath, "conf", "./conf/conf.toml", "-conf path")
}
// Init init conf
func Init() (err error) {
_, err = toml.DecodeFile(confPath, &Conf)
return
}
通過簡單的一行代碼toml.DecodeFile(confPath, &Conf),就把解析好的struct存到了&Conf里面
那么我們在main里面調用一下init:
func main() {
flag.Parse()
if err := conf.Init(); err != nil {
log.Error("conf.Init() err:%+v", err)
}
mysqlConf := conf.Conf.Mysql
fmt.Println(mysqlConf.DbName)
}
然后運行一下main函數,就可以看到控制臺中打印出了我們在conf.toml中配置的
sonofelice_db
總結
以上是生活随笔為你收集整理的Go学习笔记一:解析toml配置文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: js 压缩上传的图片方法(默认上传的是f
- 下一篇: 什么是“GB/T ”? 计算机术语你又知