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

被折叠的 条评论
为什么被折叠?



