本文系做者原创,转载请注明出处http://www.javashuo.com/article/p-gqbwblpj-en.html 。html
一些mysql或者日志路径的信息须要放在配置文件中。那么本博文主要介绍go对toml文件的解析。mysql
使用了 "github.com/BurntSushi/toml" 标准库。git
1 toml文件的写法github
[Mysql] UserName = "sonofelice" Password = "123456" IpHost = "127.0.0.1:8902" DbName = "sonofelice_db"
2 对toml文件的解析sql
为了要解析上面的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里面spa
那么咱们在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中配置的code
sonofelice_db