From b7fc6ea133b741866a8b94419e21de9d8ecd024b Mon Sep 17 00:00:00 2001 From: xiabin Date: Wed, 15 Jan 2025 10:21:51 +0800 Subject: [PATCH] =?UTF-8?q?=E6=95=B0=E6=8D=AE=E5=BA=93=E7=8E=AF=E5=A2=83?= =?UTF-8?q?=E5=8F=98=E9=87=8F=E8=8E=B7=E5=8F=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pkg/config/viper.go | 46 +++++++++++++++++++++++++++++++++++++++++++++ pkg/db/gorm.go | 19 +++++++++++-------- 2 files changed, 57 insertions(+), 8 deletions(-) diff --git a/pkg/config/viper.go b/pkg/config/viper.go index d974367..8f8d82e 100644 --- a/pkg/config/viper.go +++ b/pkg/config/viper.go @@ -10,14 +10,35 @@ const ( LogFormatKey = "LOG_FORMAT" // 日志格式 PortKey = "PORT" // 端口 AppEnvKey = "APP_ENV" // 环境 + + DBUserNameKey = "DB_USERNAME" // 数据库用户名 + DBPasswordKey = "DB_PASSWORD" // 数据库密码 + DBHostKey = "DB_HOST" // 数据库地址 + DBPortKey = "DB_PORT" // 数据库端口 + DBNameKey = "DB_NAME" // 数据库名 ) func init() { + // 设置默认值 + + // 日志 viper.SetDefault(LogLevelKey, "debug") viper.SetDefault(LogPathKey, "./data/logs/ecpm.log") viper.SetDefault(LogFormatKey, "json") + + // 端口 viper.SetDefault(PortKey, "8080") + + // 环境 viper.SetDefault(AppEnvKey, "") + + // 数据库 + viper.SetDefault(DBUserNameKey, "root") + viper.SetDefault(DBPasswordKey, "youtu!0113") + viper.SetDefault(DBHostKey, "localhost") + viper.SetDefault(DBPortKey, "3306") + viper.SetDefault(DBNameKey, "ecpm") + viper.AutomaticEnv() } @@ -45,3 +66,28 @@ func GetPort() string { func GetAppEnv() string { return viper.GetString(AppEnvKey) } + +// GetDBUserName 获取数据库用户名 +func GetDBUserName() string { + return viper.GetString(DBUserNameKey) +} + +// GetDBPassword 获取数据库密码 +func GetDBPassword() string { + return viper.GetString(DBPasswordKey) +} + +// GetDBHost 获取数据库地址 +func GetDBHost() string { + return viper.GetString(DBHostKey) +} + +// GetDBPort 获取数据库端口 +func GetDBPort() int { + return viper.GetInt(DBPortKey) +} + +// GetDBName 获取数据库名 +func GetDBName() string { + return viper.GetString(DBNameKey) +} diff --git a/pkg/db/gorm.go b/pkg/db/gorm.go index 5b9bc3c..0d4014d 100644 --- a/pkg/db/gorm.go +++ b/pkg/db/gorm.go @@ -4,23 +4,26 @@ import ( "fmt" "gorm.io/driver/mysql" "gorm.io/gorm" + "youtu_ecpm/pkg/config" ) var Db *gorm.DB func init() { //配置MySQL连接参数 - username := "root" //账号 - password := "youtu!0113" //密码 - host := "localhost" //数据库地址,可以是Ip或者域名 - port := 3306 //数据库端口 - Dbname := "ecpm" //数据库名 - dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", username, password, host, port, Dbname) - fmt.Println(dsn) + dsn := fmt.Sprintf( + "%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", + config.GetDBUserName(), //账号 + config.GetDBPassword(), //密码 + config.GetDBHost(), //数据库地址,可以是Ip或者域名 + config.GetDBPort(), //数据库端口 + config.GetDBName(), //数据库名 + ) + + //创建数据库连接 db, err := gorm.Open(mysql.Open(dsn)) if err != nil { panic("连接数据库失败, error=" + err.Error()) } Db = db - }