Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: 重构初始化代码并调整路由组 #20

Merged
merged 4 commits into from
Nov 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions app/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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) {
Expand All @@ -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{})
Expand Down
2 changes: 1 addition & 1 deletion app/services/userCenterService/fetch.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 响应
Expand Down
4 changes: 0 additions & 4 deletions app/utils/log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)) // 添加堆栈跟踪
}
Expand Down
9 changes: 5 additions & 4 deletions app/utils/request/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"time"

"github.com/go-resty/resty/v2"
jsoniter "github.com/json-iterator/go"
"go.uber.org/zap"
)

Expand All @@ -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)
Expand All @@ -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
Expand Down
25 changes: 11 additions & 14 deletions config.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand All @@ -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 # 是否压缩日志文件
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 # 是否压缩日志文件
1 change: 0 additions & 1 deletion config/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions config/objectStorage/minio.go
Original file line number Diff line number Diff line change
@@ -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 结构体定义
Expand Down Expand Up @@ -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{
Expand Down
25 changes: 0 additions & 25 deletions config/redis/config.go

This file was deleted.

28 changes: 18 additions & 10 deletions config/redis/redis.go
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -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
}
47 changes: 31 additions & 16 deletions config/router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}
64 changes: 0 additions & 64 deletions config/session/config.go

This file was deleted.

Loading