From 9f2b84b81b968d963931fb53001f5a2f6b9b3cdf Mon Sep 17 00:00:00 2001 From: SugarMGP <2350745751@qq.com> Date: Tue, 26 Nov 2024 17:17:04 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E9=87=8D=E6=9E=84=E5=88=9D?= =?UTF-8?q?=E5=A7=8B=E5=8C=96=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/config/config.go | 10 +++---- app/utils/log/log.go | 4 --- config.example.yaml | 25 +++++++--------- config/config/config.go | 1 - config/redis/config.go | 25 ---------------- config/redis/redis.go | 28 +++++++++++------- config/session/config.go | 61 --------------------------------------- config/session/memory.go | 12 -------- config/session/redis.go | 26 ----------------- config/session/session.go | 30 ++++++++++++------- config/wechat/config.go | 32 -------------------- config/wechat/redis.go | 19 ------------ config/wechat/wechat.go | 43 ++++++++++++--------------- go.mod | 1 - go.sum | 2 -- main.go | 6 ++-- 16 files changed, 74 insertions(+), 251 deletions(-) delete mode 100644 config/redis/config.go delete mode 100644 config/session/config.go delete mode 100644 config/session/memory.go delete mode 100644 config/session/redis.go delete mode 100644 config/wechat/config.go delete mode 100644 config/wechat/redis.go diff --git a/app/config/config.go b/app/config/config.go index e4500ea..8a4366a 100644 --- a/app/config/config.go +++ b/app/config/config.go @@ -16,7 +16,7 @@ var ctx = context.Background() // getConfig 从 Redis 获取配置,如果不存在则从数据库中获取,并缓存到 Redis func getConfig(key string) string { - val, err := redis.RedisClient.Get(ctx, key).Result() + val, err := redis.GlobalClient.Get(ctx, key).Result() if err == nil { return val } @@ -27,13 +27,13 @@ func getConfig(key string) string { Key: key, }).First(&config) - redis.RedisClient.Set(ctx, key, config.Value, 0) + redis.GlobalClient.Set(ctx, key, config.Value, 0) return config.Value } // setConfig 设置指定的配置项,如果不存在则创建新的配置。 func setConfig(key, value string) error { - redis.RedisClient.Set(ctx, key, value, 0) + redis.GlobalClient.Set(ctx, key, value, 0) var config models.Config result := database.DB.Where("`key` = ?", key).First(&config) if result.Error != nil && !errors.Is(result.Error, gorm.ErrRecordNotFound) { @@ -56,12 +56,12 @@ func setConfig(key, value string) error { // checkConfig 检查指定的配置项是否存在于 Redis 中。 func checkConfig(key string) bool { - intCmd := redis.RedisClient.Exists(ctx, key) + intCmd := redis.GlobalClient.Exists(ctx, key) return intCmd.Val() == 1 } func delConfig(key string) error { - redis.RedisClient.Del(ctx, key) + redis.GlobalClient.Del(ctx, key) res := database.DB.Where(&models.Config{ Key: key, }).Delete(models.Config{}) diff --git a/app/utils/log/log.go b/app/utils/log/log.go index 5f56201..9223405 100644 --- a/app/utils/log/log.go +++ b/app/utils/log/log.go @@ -166,10 +166,6 @@ func createEncoder(cfg *Config) zapcore.Encoder { // addAdditionalOptions 添加额外的选项 func addAdditionalOptions(cfg *Config, options *[]zap.Option) { - if !cfg.DisableCaller { - *options = append(*options, zap.AddCallerSkip(1)) // 添加调用方要求 - *options = append(*options, zap.AddCaller()) // 添加调用方信息 - } if !cfg.DisableStacktrace { *options = append(*options, zap.AddStacktrace(zapcore.ErrorLevel)) // 添加堆栈跟踪 } diff --git a/config.example.yaml b/config.example.yaml index d4cf945..7c7c26e 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -11,20 +11,18 @@ database: session: name: 4u-session - driver: redis + secret: secret redis: host: "127.0.0.1" port: 6379 db: 0 - user: root pass: wechat: # 微信小程序相关配置 (切记不能泄漏,不能为空) appid: appsecret: - user: host: @@ -34,21 +32,20 @@ admin: minio: # minio 存储配置 accessKey: # 用于身份验证的访问密钥 secretKey: # 用于身份验证的秘密密钥 - secure: False # 是否使用 HTTPS,false 表示使用 HTTP + secure: false # 是否使用 HTTPS,false 表示使用 HTTP endPoint: 127.0.0.1:9000 # MinIO 服务的地址和端口 bucket: 4uonline # 用于存储对象的桶名称 domain: http://127.0.0.1:9000/ # 对外访问的域名 tempDir: tmp # 临时对象存放目录名 log: - development: true # 是否开启开发模式 true: 开启 false: 关闭 - disableCaller: false # 是否禁用调用方 + development: true # 是否开启开发模式 true: 开启 false: 关闭 disableStacktrace: false # 是否禁用堆栈跟踪 - encoding: "json" # 编码格式 json: json格式 console: 控制台格式 - level: "info" # 日志级别 debug: 调试 info: 信息 warn: 警告 error: 错误 dpanic: 严重 panic: 恐慌 fatal: 致命 - name: "4u" # 日志名称 - writers: "console,file" # 日志输出方式 console: 控制台 file: 文件 - loggerDir: "./logs" # 日志目录 - logMaxSize: 10 # 单个日志文件最大大小 单位: MB - logMaxAge: 7 # 日志保留天数 - logCompress: false # 是否压缩日志文件 \ No newline at end of file + encoding: "json" # 编码格式 json: json格式 console: 控制台格式 + level: "info" # 日志级别 debug: 调试 info: 信息 warn: 警告 error: 错误 dpanic: 严重 panic: 恐慌 fatal: 致命 + name: "4u" # 日志名称 + writers: "console,file" # 日志输出方式 console: 控制台 file: 文件 + loggerDir: "./logs" # 日志目录 + logMaxSize: 10 # 单个日志文件最大大小 单位: MB + logMaxAge: 7 # 日志保留天数 + logCompress: false # 是否压缩日志文件 \ No newline at end of file diff --git a/config/config/config.go b/config/config/config.go index 96cc85c..74906aa 100644 --- a/config/config/config.go +++ b/config/config/config.go @@ -14,7 +14,6 @@ func init() { Config.SetConfigName("config") Config.SetConfigType("yaml") Config.AddConfigPath(".") - Config.WatchConfig() // 自动将配置读入Config变量 err := Config.ReadInConfig() if err != nil { log.Fatal("Config not find", err) diff --git a/config/redis/config.go b/config/redis/config.go deleted file mode 100644 index 829e6b3..0000000 --- a/config/redis/config.go +++ /dev/null @@ -1,25 +0,0 @@ -package redis - -import "4u-go/config/config" - -func getConfig() redisConfig { - info := redisConfig{ - Host: "localhost", - Port: "6379", - DB: 0, - Password: "", - } - if config.Config.IsSet("redis.host") { - info.Host = config.Config.GetString("redis.host") - } - if config.Config.IsSet("redis.port") { - info.Port = config.Config.GetString("redis.port") - } - if config.Config.IsSet("redis.db") { - info.DB = config.Config.GetInt("redis.db") - } - if config.Config.IsSet("redis.pass") { - info.Password = config.Config.GetString("redis.pass") - } - return info -} diff --git a/config/redis/redis.go b/config/redis/redis.go index 3aac6f1..cc5207b 100644 --- a/config/redis/redis.go +++ b/config/redis/redis.go @@ -1,6 +1,9 @@ package redis -import "github.com/go-redis/redis/v8" +import ( + "4u-go/config/config" + "github.com/go-redis/redis/v8" +) // redisConfig 定义 Redis 数据库的配置结构体 type redisConfig struct { @@ -10,20 +13,25 @@ type redisConfig struct { Password string } -// RedisClient 是全局的 Redis 客户端实例 -var RedisClient *redis.Client +// GlobalClient 全局 Redis 客户端实例 +var GlobalClient *redis.Client -// RedisInfo 保存当前 Redis 配置信息 -var RedisInfo redisConfig +// InfoConfig 保存 Redis 配置信息 +var InfoConfig redisConfig -// init 函数用于初始化 Redis 客户端和配置信息 -func init() { - info := getConfig() +// Init 函数用于初始化 Redis 客户端和配置信息 +func Init() { + info := redisConfig{ + Host: config.Config.GetString("redis.host"), + Port: config.Config.GetString("redis.port"), + DB: config.Config.GetInt("redis.db"), + Password: config.Config.GetString("redis.pass"), + } - RedisClient = redis.NewClient(&redis.Options{ + GlobalClient = redis.NewClient(&redis.Options{ Addr: info.Host + ":" + info.Port, Password: info.Password, DB: info.DB, }) - RedisInfo = info + InfoConfig = info } diff --git a/config/session/config.go b/config/session/config.go deleted file mode 100644 index 9e4e6d0..0000000 --- a/config/session/config.go +++ /dev/null @@ -1,61 +0,0 @@ -package session - -import ( - "strings" - - "4u-go/config/config" -) - -// 定义会话驱动类型常量 -const ( - Memory = "memory" - Redis = "redis" -) - -// 默认会话名称 -var defaultName = "wejh-session" - -// sessionConfig 存储会话的配置 -type sessionConfig struct { - Driver string - Name string -} - -// getConfig 获取会话配置 -func getConfig() sessionConfig { - wc := sessionConfig{} - wc.Driver = Memory - if config.Config.IsSet("session.driver") { - wc.Driver = strings.ToLower(config.Config.GetString("session.driver")) - } - - wc.Name = defaultName - if config.Config.IsSet("session.name") { - wc.Name = strings.ToLower(config.Config.GetString("session.name")) - } - - return wc -} - -// getRedisConfig 获取 Redis 配置 -func getRedisConfig() redisConfig { - info := redisConfig{ - Host: "localhost", - Port: "6379", - DB: 0, - Password: "", - } - if config.Config.IsSet("redis.host") { - info.Host = config.Config.GetString("redis.host") - } - if config.Config.IsSet("redis.port") { - info.Port = config.Config.GetString("redis.port") - } - if config.Config.IsSet("redis.db") { - info.DB = config.Config.GetInt("redis.db") - } - if config.Config.IsSet("redis.pass") { - info.Password = config.Config.GetString("redis.pass") - } - return info -} diff --git a/config/session/memory.go b/config/session/memory.go deleted file mode 100644 index 17efd53..0000000 --- a/config/session/memory.go +++ /dev/null @@ -1,12 +0,0 @@ -package session - -import ( - "github.com/gin-contrib/sessions" - "github.com/gin-contrib/sessions/memstore" - "github.com/gin-gonic/gin" -) - -func setMemory(r *gin.Engine, name string) { - store := memstore.NewStore() - r.Use(sessions.Sessions(name, store)) -} diff --git a/config/session/redis.go b/config/session/redis.go deleted file mode 100644 index 26cd036..0000000 --- a/config/session/redis.go +++ /dev/null @@ -1,26 +0,0 @@ -package session - -import ( - "fmt" - - "github.com/gin-contrib/sessions" - sessionRedis "github.com/gin-contrib/sessions/redis" - "github.com/gin-gonic/gin" -) - -type redisConfig struct { - Host string - Port string - DB int - Password string -} - -func setRedis(r *gin.Engine, name string) error { - info := getRedisConfig() - store, err := sessionRedis.NewStore(10, "tcp", info.Host+":"+info.Port, info.Password, []byte("secret")) - if err != nil { - return fmt.Errorf("redis session init failed: %w", err) // 返回包装后的错误 - } - r.Use(sessions.Sessions(name, store)) - return nil -} diff --git a/config/session/session.go b/config/session/session.go index 3fb26d7..6f19cc9 100644 --- a/config/session/session.go +++ b/config/session/session.go @@ -1,22 +1,30 @@ package session import ( - "errors" + "fmt" + "strconv" + "4u-go/config/config" + "4u-go/config/redis" + "github.com/gin-contrib/sessions" + sessionRedis "github.com/gin-contrib/sessions/redis" "github.com/gin-gonic/gin" ) -// Init 初始化会话管理,设置会话存储驱动 +// Init 使用 Redis 初始化会话管理 func Init(r *gin.Engine) error { - config := getConfig() - switch config.Driver { - case Redis: - return setRedis(r, config.Name) - case Memory: - setMemory(r, config.Name) - default: - return errors.New("session config error") - } + info := redis.InfoConfig + name := config.Config.GetString("session.name") + secret := config.Config.GetString("session.secret") + store, err := sessionRedis.NewStoreWithDB(10, "tcp", + info.Host+":"+info.Port, info.Password, + strconv.Itoa(info.DB), + []byte(secret), + ) + if err != nil { + return fmt.Errorf("session init failed: %w", err) + } + r.Use(sessions.Sessions(name, store)) return nil } diff --git a/config/wechat/config.go b/config/wechat/config.go deleted file mode 100644 index 67511ae..0000000 --- a/config/wechat/config.go +++ /dev/null @@ -1,32 +0,0 @@ -package wechat - -import ( - "errors" - "strings" - - "4u-go/config/config" -) - -type wechatConfig struct { - Driver string - AppId string - AppSecret string -} - -func getConfigs() (wechatConfig, error) { - wc := wechatConfig{} - if !config.Config.IsSet("wechat.appid") { - return wc, errors.New("wechat.appid config error") - } - if !config.Config.IsSet("wechat.appsecret") { - return wc, errors.New("wechat.appsecret config error") - } - wc.AppId = config.Config.GetString("wechat.appid") - wc.AppSecret = config.Config.GetString("wechat.appsecret") - - wc.Driver = Memory - if config.Config.IsSet("wechat.driver") { - wc.Driver = strings.ToLower(config.Config.GetString("wechat.driver")) - } - return wc, nil -} diff --git a/config/wechat/redis.go b/config/wechat/redis.go deleted file mode 100644 index ef147ed..0000000 --- a/config/wechat/redis.go +++ /dev/null @@ -1,19 +0,0 @@ -package wechat - -import ( - "context" - - "4u-go/config/redis" - "github.com/silenceper/wechat/v2/cache" -) - -func setRedis() cache.Cache { - redisOpts := &cache.RedisOpts{ - Host: redis.RedisInfo.Host + ":" + redis.RedisInfo.Port, - Database: redis.RedisInfo.DB, - MaxActive: 10, - MaxIdle: 10, - IdleTimeout: 60, - } - return cache.NewRedis(context.Background(), redisOpts) -} diff --git a/config/wechat/wechat.go b/config/wechat/wechat.go index c5ec31d..e56b086 100644 --- a/config/wechat/wechat.go +++ b/config/wechat/wechat.go @@ -1,46 +1,39 @@ package wechat import ( - "errors" + "context" - wechat "github.com/silenceper/wechat/v2" + "4u-go/config/config" + "4u-go/config/redis" + "github.com/silenceper/wechat/v2" "github.com/silenceper/wechat/v2/cache" "github.com/silenceper/wechat/v2/miniprogram" miniConfig "github.com/silenceper/wechat/v2/miniprogram/config" ) -// 定义支持的驱动类型常量 -const ( - Memory = "memory" - Redis = "redis" -) - // MiniProgram 是一个指向小程序实例的指针 var MiniProgram *miniprogram.MiniProgram // Init 初始化微信小程序配置。 -func Init() error { - config, err := getConfigs() - if err != nil { - return err - } +func Init() { + info := redis.InfoConfig + appId := config.Config.GetString("wechat.appid") + appSecret := config.Config.GetString("wechat.appsecret") + wc := wechat.NewWechat() - var wcCache cache.Cache - switch config.Driver { - case Redis: - wcCache = setRedis() - case Memory: - wcCache = cache.NewMemory() - default: - return errors.New("wechat config error") - } + wcCache := cache.NewRedis(context.Background(), &cache.RedisOpts{ + Host: info.Host + ":" + info.Port, + Database: info.DB, + MaxActive: 10, + MaxIdle: 10, + IdleTimeout: 60, + }) cfg := &miniConfig.Config{ - AppID: config.AppId, - AppSecret: config.AppSecret, + AppID: appId, + AppSecret: appSecret, Cache: wcCache, } MiniProgram = wc.GetMiniProgram(cfg) - return nil } diff --git a/go.mod b/go.mod index 88337b5..1711940 100644 --- a/go.mod +++ b/go.mod @@ -60,7 +60,6 @@ require ( github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/pelletier/go-toml/v2 v2.2.3 // indirect - github.com/quasoft/memstore v0.0.0-20191010062613-2bce066d2b0b // indirect github.com/rs/xid v1.6.0 // indirect github.com/sagikazarmark/locafero v0.6.0 // indirect github.com/sagikazarmark/slog-shim v0.1.0 // indirect diff --git a/go.sum b/go.sum index 26ca8e6..476e02c 100644 --- a/go.sum +++ b/go.sum @@ -164,8 +164,6 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/quasoft/memstore v0.0.0-20191010062613-2bce066d2b0b h1:aUNXCGgukb4gtY99imuIeoh8Vr0GSwAlYxPAhqZrpFc= -github.com/quasoft/memstore v0.0.0-20191010062613-2bce066d2b0b/go.mod h1:wTPjTepVu7uJBYgZ0SdWHQlIas582j6cn2jgk4DDdlg= github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU= diff --git a/main.go b/main.go index 375573c..2375e53 100644 --- a/main.go +++ b/main.go @@ -6,6 +6,7 @@ import ( "4u-go/config/config" "4u-go/config/database" "4u-go/config/objectStorage" + "4u-go/config/redis" "4u-go/config/router" "4u-go/config/session" "4u-go/config/wechat" @@ -25,6 +26,7 @@ func main() { r.NoMethod(midwares.HandleNotFound) r.NoRoute(midwares.HandleNotFound) log.ZapInit() + redis.Init() if err := database.Init(); err != nil { zap.L().Fatal(err.Error()) } @@ -34,9 +36,7 @@ func main() { if err := session.Init(r); err != nil { zap.L().Fatal(err.Error()) } - if err := wechat.Init(); err != nil { - zap.L().Fatal(err.Error()) - } + wechat.Init() router.Init(r) err := r.Run(":" + config.Config.GetString("server.port"))