本文系作者原創,轉載請注明出處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