From a0be99ce872533e8b79b72bd72ed65cca37599c1 Mon Sep 17 00:00:00 2001 From: SugarMGP <2350745751@qq.com> Date: Sun, 24 Nov 2024 17:02:32 +0800 Subject: [PATCH 1/4] =?UTF-8?q?style:=20=E7=AE=80=E5=8C=96=E5=B9=B6?= =?UTF-8?q?=E7=BB=9F=E4=B8=80=E5=88=9D=E5=A7=8B=E5=8C=96=E4=BB=A3=E7=A0=81?= =?UTF-8?q?=E9=A3=8E=E6=A0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/objectStorage/minio.go | 4 ++-- config/session/config.go | 9 +++------ config/session/session.go | 8 ++++---- config/wechat/config.go | 8 ++++---- config/wechat/wechat.go | 15 ++++++--------- main.go | 2 +- 6 files changed, 20 insertions(+), 26 deletions(-) diff --git a/config/objectStorage/minio.go b/config/objectStorage/minio.go index c1cb82d..dd56f37 100644 --- a/config/objectStorage/minio.go +++ b/config/objectStorage/minio.go @@ -1,12 +1,12 @@ package objectStorage import ( + "fmt" "strings" "4u-go/config/config" "github.com/minio/minio-go/v7" "github.com/minio/minio-go/v7/pkg/credentials" - "github.com/sirupsen/logrus" ) // MinioCreateTempDirServant 结构体定义 @@ -37,7 +37,7 @@ func Init() error { Secure: secure, }) if err != nil { - logrus.Fatalf("objectStorage.minio 创建客户端失败: %s", err) + return fmt.Errorf("minio initialization failed: %w", err) } MinioService = &MinioCreateTempDirServant{ diff --git a/config/session/config.go b/config/session/config.go index c85ccbc..9e4e6d0 100644 --- a/config/session/config.go +++ b/config/session/config.go @@ -6,13 +6,10 @@ import ( "4u-go/config/config" ) -// 定义会话驱动类型 -type driver string - // 定义会话驱动类型常量 const ( - Memory driver = "memory" - Redis driver = "redis" + Memory = "memory" + Redis = "redis" ) // 默认会话名称 @@ -27,7 +24,7 @@ type sessionConfig struct { // getConfig 获取会话配置 func getConfig() sessionConfig { wc := sessionConfig{} - wc.Driver = string(Memory) + wc.Driver = Memory if config.Config.IsSet("session.driver") { wc.Driver = strings.ToLower(config.Config.GetString("session.driver")) } diff --git a/config/session/session.go b/config/session/session.go index 0a6bf71..3fb26d7 100644 --- a/config/session/session.go +++ b/config/session/session.go @@ -1,7 +1,7 @@ package session import ( - "fmt" + "errors" "github.com/gin-gonic/gin" ) @@ -10,12 +10,12 @@ import ( func Init(r *gin.Engine) error { config := getConfig() switch config.Driver { - case string(Redis): + case Redis: return setRedis(r, config.Name) - case string(Memory): + case Memory: setMemory(r, config.Name) default: - return fmt.Errorf("session configError") + return errors.New("session config error") } return nil diff --git a/config/wechat/config.go b/config/wechat/config.go index cc58044..67511ae 100644 --- a/config/wechat/config.go +++ b/config/wechat/config.go @@ -1,7 +1,7 @@ package wechat import ( - "fmt" + "errors" "strings" "4u-go/config/config" @@ -16,15 +16,15 @@ type wechatConfig struct { func getConfigs() (wechatConfig, error) { wc := wechatConfig{} if !config.Config.IsSet("wechat.appid") { - return wc, fmt.Errorf("wechat.appid configError") + return wc, errors.New("wechat.appid config error") } if !config.Config.IsSet("wechat.appsecret") { - return wc, fmt.Errorf("wechat.appsecret configError") + return wc, errors.New("wechat.appsecret config error") } wc.AppId = config.Config.GetString("wechat.appid") wc.AppSecret = config.Config.GetString("wechat.appsecret") - wc.Driver = string(Memory) + wc.Driver = Memory if config.Config.IsSet("wechat.driver") { wc.Driver = strings.ToLower(config.Config.GetString("wechat.driver")) } diff --git a/config/wechat/wechat.go b/config/wechat/wechat.go index a7e9469..c5ec31d 100644 --- a/config/wechat/wechat.go +++ b/config/wechat/wechat.go @@ -1,7 +1,7 @@ package wechat import ( - "fmt" + "errors" wechat "github.com/silenceper/wechat/v2" "github.com/silenceper/wechat/v2/cache" @@ -9,13 +9,10 @@ import ( miniConfig "github.com/silenceper/wechat/v2/miniprogram/config" ) -// driver 类型表示会话存储驱动的名称 -type driver string - // 定义支持的驱动类型常量 const ( - Memory driver = "memory" - Redis driver = "redis" + Memory = "memory" + Redis = "redis" ) // MiniProgram 是一个指向小程序实例的指针 @@ -30,12 +27,12 @@ func Init() error { wc := wechat.NewWechat() var wcCache cache.Cache switch config.Driver { - case string(Redis): + case Redis: wcCache = setRedis() - case string(Memory): + case Memory: wcCache = cache.NewMemory() default: - return fmt.Errorf("wechat configError") + return errors.New("wechat config error") } cfg := &miniConfig.Config{ diff --git a/main.go b/main.go index 5cb544e..375573c 100644 --- a/main.go +++ b/main.go @@ -26,7 +26,7 @@ func main() { r.NoRoute(midwares.HandleNotFound) log.ZapInit() if err := database.Init(); err != nil { - zap.L().Fatal(err.Error()) // 在 main 函数中处理错误并终止程序 + zap.L().Fatal(err.Error()) } if err := objectStorage.Init(); err != nil { zap.L().Fatal(err.Error()) From dc849ae6575461ccdbd0db5aa31ff282e3ca153e Mon Sep 17 00:00:00 2001 From: SugarMGP <2350745751@qq.com> Date: Sun, 24 Nov 2024 17:17:01 +0800 Subject: [PATCH 2/4] =?UTF-8?q?perf:=20=E4=BC=98=E5=8C=96=20Resty=20?= =?UTF-8?q?=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/services/userCenterService/fetch.go | 2 +- app/utils/request/request.go | 9 +++++---- go.mod | 4 ++-- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/app/services/userCenterService/fetch.go b/app/services/userCenterService/fetch.go index b46e3c6..d7b8f52 100644 --- a/app/services/userCenterService/fetch.go +++ b/app/services/userCenterService/fetch.go @@ -15,7 +15,7 @@ type UserCenterResponse struct { // FetchHandleOfPost 向用户中心发送 POST 请求 func FetchHandleOfPost(form map[string]any, url string) (*UserCenterResponse, error) { - client := request.New() + client := request.NewUnSafe() var rc UserCenterResponse // 发送 POST 请求并自动解析 JSON 响应 diff --git a/app/utils/request/request.go b/app/utils/request/request.go index 0e490d6..8034c29 100644 --- a/app/utils/request/request.go +++ b/app/utils/request/request.go @@ -6,6 +6,7 @@ import ( "time" "github.com/go-resty/resty/v2" + jsoniter "github.com/json-iterator/go" "go.uber.org/zap" ) @@ -18,9 +19,9 @@ type Client struct { func New() Client { s := Client{ Client: resty.New(). - SetTimeout(10 * time.Second). - SetRetryCount(3). - SetRetryWaitTime(2 * time.Second), + SetTimeout(5 * time.Second). + SetJSONMarshaler(jsoniter.ConfigCompatibleWithStandardLibrary.Marshal). + SetJSONUnmarshaler(jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal), } // 利用中间件实现请求日志 s.OnAfterResponse(RestyLogMiddleware) @@ -47,7 +48,7 @@ func RestyLogMiddleware(_ *resty.Client, resp *resty.Response) error { zap.L().Warn("请求出现错误", zap.String("method", method), zap.String("url", url), - zap.Float64("time_spent", resp.Time().Seconds()), + zap.Int64("time_spent(ms)", resp.Time().Milliseconds()), ) } return nil diff --git a/go.mod b/go.mod index 3eef19c..88337b5 100644 --- a/go.mod +++ b/go.mod @@ -10,11 +10,11 @@ require ( github.com/gin-gonic/gin v1.10.0 github.com/go-redis/redis/v8 v8.11.5 github.com/go-resty/resty/v2 v2.16.0 + github.com/json-iterator/go v1.1.12 github.com/minio/minio-go/v7 v7.0.80 github.com/pkg/errors v0.9.1 github.com/satori/go.uuid v1.2.0 github.com/silenceper/wechat/v2 v2.1.7 - github.com/sirupsen/logrus v1.9.3 github.com/spf13/viper v1.19.0 go.uber.org/zap v1.27.0 golang.org/x/crypto v0.29.0 @@ -50,7 +50,6 @@ require ( github.com/hashicorp/hcl v1.0.0 // indirect github.com/jinzhu/inflection v1.0.0 // indirect github.com/jinzhu/now v1.1.5 // indirect - github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/compress v1.17.11 // indirect github.com/klauspost/cpuid/v2 v2.2.9 // indirect github.com/leodido/go-urn v1.4.0 // indirect @@ -65,6 +64,7 @@ require ( 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 + github.com/sirupsen/logrus v1.9.3 // indirect github.com/sourcegraph/conc v0.3.0 // indirect github.com/spf13/afero v1.11.0 // indirect github.com/spf13/cast v1.7.0 // indirect From cdcda1b786bf4257450a6b1338df2b741e93aa7c Mon Sep 17 00:00:00 2001 From: SugarMGP <2350745751@qq.com> Date: Tue, 26 Nov 2024 11:53:03 +0800 Subject: [PATCH 3/4] =?UTF-8?q?refactor:=20=E8=B0=83=E6=95=B4=E8=B7=AF?= =?UTF-8?q?=E7=94=B1=E7=BB=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/router/router.go | 47 +++++++++++++++++++++++++++-------------- 1 file changed, 31 insertions(+), 16 deletions(-) diff --git a/config/router/router.go b/config/router/router.go index 0cf6f65..df150ea 100644 --- a/config/router/router.go +++ b/config/router/router.go @@ -36,42 +36,57 @@ func Init(r *gin.Engine) { admin := api.Group("/admin") { admin.POST("/create/key", adminController.CreateAdminByKey) + + adminActivity := admin.Group("/activity", midwares.CheckAdmin) + { + adminActivity.POST("", activityController.CreateActivity) + adminActivity.PUT("", activityController.UpdateActivity) + adminActivity.DELETE("", activityController.DeleteActivity) + } + + adminAnnouncement := admin.Group("/announcement", midwares.CheckAdmin) + { + adminAnnouncement.POST("", announcementController.CreateAnnouncement) + adminAnnouncement.PUT("", announcementController.UpdateAnnouncement) + adminAnnouncement.DELETE("", announcementController.DeleteAnnouncement) + } + + adminCollege := admin.Group("/college", midwares.CheckSuperAdmin) + { + adminCollege.POST("", collegeController.CreateCollege) + adminCollege.PUT("", collegeController.UpdateCollege) + adminCollege.DELETE("", collegeController.DeleteCollege) + } + + adminWebsite := admin.Group("/website", midwares.CheckAdmin) + { + adminWebsite.POST("", websiteController.CreateWebsite) + adminWebsite.DELETE("", websiteController.DeleteWebsite) + adminWebsite.PUT("", websiteController.UpdateWebsite) + adminWebsite.GET("/list", websiteController.GetEditableWebsites) + } } activity := api.Group("/activity") { activity.GET("/list", activityController.GetActivityList) activity.GET("", activityController.GetActivity) - activity.POST("", midwares.CheckAdmin, activityController.CreateActivity) - activity.PUT("", midwares.CheckAdmin, activityController.UpdateActivity) - activity.DELETE("", midwares.CheckAdmin, activityController.DeleteActivity) } announcement := api.Group("/announcement") { announcement.GET("/list", announcementController.GetAnnouncementList) announcement.GET("", announcementController.GetAnnouncement) - announcement.POST("", midwares.CheckAdmin, announcementController.CreateAnnouncement) - announcement.PUT("", midwares.CheckAdmin, announcementController.UpdateAnnouncement) - announcement.DELETE("", midwares.CheckAdmin, announcementController.DeleteAnnouncement) } college := api.Group("/college") { - college.GET("", collegeController.GetCollegeList) - college.POST("", midwares.CheckSuperAdmin, collegeController.CreateCollege) - college.PUT("", midwares.CheckSuperAdmin, collegeController.UpdateCollege) - college.DELETE("", midwares.CheckSuperAdmin, collegeController.DeleteCollege) + college.GET("/list", collegeController.GetCollegeList) } website := api.Group("/website") { - website.GET("", websiteController.GetWebsiteList) - website.POST("", midwares.CheckAdmin, websiteController.CreateWebsite) - website.DELETE("", midwares.CheckAdmin, websiteController.DeleteWebsite) - website.PUT("", midwares.CheckAdmin, websiteController.UpdateWebsite) - - website.GET("/admin", midwares.CheckAdmin, websiteController.GetEditableWebsites) + website.GET("/list", websiteController.GetWebsiteList) } } } 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 4/4] =?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"))