我们在后端开发中,需要一个配置文件来存储或初使化变量属性,像 Django 的有个封装好全局的配置文件settings.py,Flask 中也有类似的。但是在 Golang 中要自己实现或使用第三方的包,这里我介绍两种我开发中常使用的方式。
先来说一种简单暴力的方式:godotenv
使用方法很简单
1:在你启动程序的同级目录下建一个 .env 文件即可,然后各项配置写入此文件中,内容格式如下:
dbUser="root"
dbPwd="123456"
dbHost="127.0.0.1"
dbPort="3306"
db="godevops"
2:加载配置文件
在你需要使用变量的时候只要运行 godotenv.Load() 即可
3:获取配置值
dbUser := os.Getenv("dbUser")
下面再说说另外一包更强大的包:viper
以加载yaml文件格式为例,下面看一个示例:
web:
static_path:
port: 8080
domain: 127.0.0.1:8080
read_timeout: 5
write_timeout: 5
idle_timeout: 5
gorm:
debug: true
db_type: sqlite3
max_lifetime: 7200
max_open_conns: 150
max_idle_conns: 50
table_prefix: tb_
mysql:
host: 127.0.0.1
port: 3306
user: root
password: 123456
db_name: goapp
parameters: charset=utf8&parseTime=True&loc=Asia%2FShanghai
下面看看viper使用一个示例:
首先我们定义一个结构体用于存放各配置项section
// Config 配置参数
type Config struct {
Web Web
Gorm Gorm
MySQL MySQL
}
v := viper.New()
v.SetConfigFile("config.yaml")
v.SetConfigType("yaml")
if err1 := v.ReadInConfig(); err1 != nil {
err = err1
return
}
c = &Config{}
c.Web.StaticPath = v.GetString("web.static_path")
c.Web.Domain = v.GetString("web.domain")
c.Web.Port = v.GetInt("web.port")
c.Web.ReadTimeout = v.GetInt("web.read_timeout")
c.Web.WriteTimeout = v.GetInt("web.write_timeout")
c.Web.IdleTimeout = v.GetInt("web.idle_timeout")
c.MySQL.Host = v.GetString("mysql.host")
c.MySQL.Port = v.GetInt("mysql.port")
c.MySQL.User = v.GetString("mysql.user")
c.MySQL.Password = v.GetString("mysql.password")
c.MySQL.DBName = v.GetString("mysql.db_name")
c.MySQL.Parameters = v.GetString("mysql.parameters")
c.Gorm.Debug = v.GetBool("gorm.debug")
c.Gorm.DBType = v.GetString("gorm.db_type")
c.Gorm.MaxLifetime = v.GetInt("gorm.max_lifetime")
c.Gorm.MaxOpenConns = v.GetInt("gorm.max_open_conns")
c.Gorm.MaxIdleConns = v.GetInt("gorm.max_idle_conns")
c.Gorm.TablePrefix = v.GetString("gorm.table_prefix")
在实际使用中,我们可以把以上代码封装在一个函数中,然后返回一个 c *config.Config 结构体对象。在其它方法调用的时候,把返回值传入即可!