• 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
  • 相关阅读:
    求超大文件上传方案( vue )
    求超大文件上传方案( csharp )
    求超大文件上传方案( c# )
    求超大文件上传方案( .net )
    求超大文件上传方案( asp.net )
    求超大文件上传方案( php )
    求超大文件上传方案( jsp )
    用浏览器 实现断点续传 (HTTP)
    shuffle() 函数
    no.random.randn
  • 原文地址:https://www.cnblogs.com/sonofelice/p/9085291.html
Copyright © 2020-2023  润新知