1.0
This commit is contained in:
@@ -0,0 +1,102 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"gopkg.in/yaml.v3"
|
||||
"os"
|
||||
)
|
||||
|
||||
var MineConfig *Config
|
||||
|
||||
// Config 应用配置结构
|
||||
type Config struct {
|
||||
App AppConfig `yaml:"app"`
|
||||
Database DatabaseConfig `yaml:"database"`
|
||||
JWT JWTConfig `yaml:"jwt"`
|
||||
Server ServerConfig `yaml:"server"`
|
||||
Log LogConfig `yaml:"log"`
|
||||
}
|
||||
|
||||
// AppConfig 应用基础配置
|
||||
type AppConfig struct {
|
||||
Name string `yaml:"name"`
|
||||
Version string `yaml:"version"`
|
||||
Port int `yaml:"port"`
|
||||
Env string `yaml:"env"`
|
||||
}
|
||||
|
||||
// DatabaseConfig 数据库配置
|
||||
type DatabaseConfig struct {
|
||||
Driver string `yaml:"driver"`
|
||||
Host string `yaml:"host"`
|
||||
Port int `yaml:"port"`
|
||||
Username string `yaml:"username"`
|
||||
Password string `yaml:"password"`
|
||||
DBName string `yaml:"dbname"`
|
||||
Charset string `yaml:"charset"`
|
||||
SQLitePath string `yaml:"sqlite_path"`
|
||||
MaxIdleConns int `yaml:"max_idle_conns"`
|
||||
MaxOpenConns int `yaml:"max_open_conns"`
|
||||
ConnMaxLifetime int `yaml:"conn_max_lifetime"`
|
||||
}
|
||||
|
||||
// JWTConfig JWT配置
|
||||
type JWTConfig struct {
|
||||
SecretKey string `yaml:"secret_key"`
|
||||
ExpireHours int `yaml:"expire_hours"`
|
||||
}
|
||||
|
||||
// ServerConfig 服务器配置
|
||||
type ServerConfig struct {
|
||||
ReadTimeout int `yaml:"read_timeout"`
|
||||
WriteTimeout int `yaml:"write_timeout"`
|
||||
StaticPath string `yaml:"static_path"`
|
||||
UploadMaxSize int `yaml:"upload_max_size"`
|
||||
}
|
||||
|
||||
// LogConfig 日志配置
|
||||
type LogConfig struct {
|
||||
Level string `yaml:"level"`
|
||||
FilePath string `yaml:"file_path"`
|
||||
MaxSize int `yaml:"max_size"`
|
||||
MaxAge int `yaml:"max_age"`
|
||||
MaxBackups int `yaml:"max_backups"`
|
||||
}
|
||||
|
||||
// LoadConfig 加载配置文件
|
||||
func LoadConfig(configPath string) (*Config, error) {
|
||||
config := &Config{}
|
||||
|
||||
// 读取配置文件
|
||||
file, err := os.ReadFile(configPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取配置文件失败: %v", err)
|
||||
}
|
||||
|
||||
// 解析YAML
|
||||
err = yaml.Unmarshal(file, config)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("解析配置文件失败: %v", err)
|
||||
}
|
||||
|
||||
// 设置全局配置
|
||||
MineConfig = config
|
||||
|
||||
return config, nil
|
||||
}
|
||||
|
||||
// GetDSN 获取数据库连接字符串
|
||||
func (db *DatabaseConfig) GetDSN() string {
|
||||
switch db.Driver {
|
||||
case "mysql":
|
||||
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=True&loc=Local",
|
||||
db.Username, db.Password, db.Host, db.Port, db.DBName, db.Charset)
|
||||
case "postgres":
|
||||
return fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%d sslmode=disable TimeZone=Asia/Shanghai",
|
||||
db.Host, db.Username, db.Password, db.DBName, db.Port)
|
||||
case "sqlite":
|
||||
return db.SQLitePath
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
var DB *gorm.DB
|
||||
|
||||
// InitDatabase 初始化数据库连接
|
||||
func InitDatabase(config *DatabaseConfig) error {
|
||||
var err error
|
||||
var dialector gorm.Dialector
|
||||
|
||||
// 根据驱动类型选择相应的方言
|
||||
switch config.Driver {
|
||||
case "mysql":
|
||||
dialector = mysql.Open(config.GetDSN())
|
||||
case "postgres":
|
||||
dialector = postgres.Open(config.GetDSN())
|
||||
case "sqlite":
|
||||
dialector = sqlite.Open(config.GetDSN())
|
||||
default:
|
||||
return fmt.Errorf("不支持的数据库驱动: %s", config.Driver)
|
||||
}
|
||||
|
||||
// GORM 配置
|
||||
gormConfig := &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Info),
|
||||
}
|
||||
|
||||
// 连接数据库
|
||||
DB, err = gorm.Open(dialector, gormConfig)
|
||||
if err != nil {
|
||||
return fmt.Errorf("连接数据库失败: %v", err)
|
||||
}
|
||||
|
||||
// 获取底层的 *sql.DB
|
||||
sqlDB, err := DB.DB()
|
||||
if err != nil {
|
||||
return fmt.Errorf("获取数据库连接失败: %v", err)
|
||||
}
|
||||
|
||||
// 设置连接池参数
|
||||
sqlDB.SetMaxIdleConns(config.MaxIdleConns)
|
||||
sqlDB.SetMaxOpenConns(config.MaxOpenConns)
|
||||
sqlDB.SetConnMaxLifetime(time.Duration(config.ConnMaxLifetime) * time.Second)
|
||||
|
||||
// 测试连接
|
||||
if err := sqlDB.Ping(); err != nil {
|
||||
return fmt.Errorf("数据库连接测试失败: %v", err)
|
||||
}
|
||||
|
||||
log.Println("数据库连接成功")
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetDB 获取数据库实例
|
||||
func GetDB() *gorm.DB {
|
||||
return DB
|
||||
}
|
||||
|
||||
// CloseDatabase 关闭数据库连接
|
||||
func CloseDatabase() error {
|
||||
sqlDB, err := DB.DB()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return sqlDB.Close()
|
||||
}
|
||||
|
||||
// AutoMigrate 自动迁移数据表
|
||||
func AutoMigrate(models ...interface{}) error {
|
||||
return DB.AutoMigrate(models...)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package common
|
||||
|
||||
type Result struct {
|
||||
Code int `json:"code"`
|
||||
Success bool `json:"success"`
|
||||
Message string `json:"message"`
|
||||
Data interface{} `json:"data"`
|
||||
}
|
||||
|
||||
func Success(data interface{}) Result {
|
||||
|
||||
return Result{200, true, "", data}
|
||||
}
|
||||
|
||||
func SuccessWithMessage(data interface{}, message string) Result {
|
||||
return Result{200, true, message, data}
|
||||
}
|
||||
|
||||
func Error(code int, message string) Result {
|
||||
return Result{code, false, message, nil}
|
||||
}
|
||||
func ErrorWithData(data interface{}, code int, message string) Result {
|
||||
return Result{code, true, message, data}
|
||||
}
|
||||
Reference in New Issue
Block a user