toml的使用示例

本文介绍了如何在Go项目中使用TOML格式编写配置文件,并提供了读取这些配置文件的Go代码示例,帮助开发者更好地管理项目设置。

1.编写配置文件 xx.toml

[email]
host="smtp.mxhichina.com"
port=465
username="xx@xx.com"
password="xxxxx"
toUsers = [ "xxxx@xx.com" ]

[server]
port=8777

[mysql]
dsn = "root:password@tcp(127.0.0.1:3306)/xxx?charset=utf8&parseTime=True&loc=Local&interpolateParams=true"
maxIdleConn = 8
maxOpenConn = 16
maxLifetime = 600

2.编写go文件读取配置

package conf

import "github.com/BurntSushi/toml"

var Conf = &config{}

func init() {
    file := "conf/xx.toml"
    if _, err := toml.DecodeFile(file, Conf); err != nil {
        panic(err)
    }
}

type config struct {
    Server *Server `toml:"server"`
    Email *Email `toml:"email"`
}

type Server struct {
    Port int64 `toml:"port"`
}

type Email struct {
    Host string `toml:"host"`
    Port int `toml:"port"`
    UserName string `toml:"username"`
    Password string `toml:"password"`
    ToUsers []string `toml:"toUsers"`
}

type Mysql struct {
    Dsn string `toml:"dsn"`
    MaxIdleConn int `toml:"maxIdleConn"`
    MaxOpenConn int `toml:"maxOpenConn"`
    MaxLifetime int  `toml:"maxLifetime"`
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值