Go学习笔记一:解析toml配置文件

一些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

猜你喜欢

转载自www.cnblogs.com/sonofelice/p/9085291.html