## 🛡️ 新增功能 - 实现完整的CORS中间件,支持开发/生产环境配置 - 实现请求日志中间件,完整的请求生命周期记录 - 实现全局错误处理中间件,统一错误响应格式 - 创建中间件管理器,支持链式中间件和配置管理 ## 🔧 技术改进 - 更新配置系统支持中间件配置 - 修复go-zero日志API兼容性问题 - 创建完整的中间件测试用例 - 编译测试通过,功能完整可用 ## 📊 进度提升 - 项目总进度从42.5%提升至50.0% - 中优先级任务完成率达55% - 3个中优先级任务同时完成 ## 🎯 完成的任务 14. 实现 CORS 中间件 16. 实现请求日志中间件 17. 完善全局错误处理 Co-authored-by: Claude Code <claude@anthropic.com>
68 lines
1.7 KiB
Go
68 lines
1.7 KiB
Go
package svc
|
|
|
|
import (
|
|
"fmt"
|
|
"gorm.io/gorm"
|
|
"photography-backend/internal/config"
|
|
"photography-backend/internal/middleware"
|
|
"photography-backend/internal/model"
|
|
"photography-backend/pkg/utils/database"
|
|
"github.com/zeromicro/go-zero/core/stores/sqlx"
|
|
)
|
|
|
|
type ServiceContext struct {
|
|
Config config.Config
|
|
DB *gorm.DB
|
|
UserModel model.UserModel
|
|
PhotoModel model.PhotoModel
|
|
CategoryModel model.CategoryModel
|
|
Middleware *middleware.MiddlewareManager
|
|
}
|
|
|
|
func NewServiceContext(c config.Config) *ServiceContext {
|
|
db, err := database.NewDB(c.Database)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
// Create sqlx connection for go-zero models
|
|
sqlxConn := sqlx.NewSqlConn(getSQLDriverName(c.Database.Driver), getSQLDataSource(c.Database))
|
|
|
|
return &ServiceContext{
|
|
Config: c,
|
|
DB: db,
|
|
UserModel: model.NewUserModel(sqlxConn),
|
|
PhotoModel: model.NewPhotoModel(sqlxConn),
|
|
CategoryModel: model.NewCategoryModel(sqlxConn),
|
|
Middleware: middleware.NewMiddlewareManager(c),
|
|
}
|
|
}
|
|
|
|
func getSQLDriverName(driver string) string {
|
|
switch driver {
|
|
case "mysql":
|
|
return "mysql"
|
|
case "postgres":
|
|
return "postgres"
|
|
case "sqlite":
|
|
return "sqlite3"
|
|
default:
|
|
return "mysql"
|
|
}
|
|
}
|
|
|
|
func getSQLDataSource(config database.Config) string {
|
|
switch config.Driver {
|
|
case "mysql":
|
|
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=True&loc=Local",
|
|
config.Username, config.Password, config.Host, config.Port, config.Database, config.Charset)
|
|
case "postgres":
|
|
return fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%d sslmode=%s TimeZone=Asia/Shanghai",
|
|
config.Host, config.Username, config.Password, config.Database, config.Port, config.SSLMode)
|
|
case "sqlite":
|
|
return config.FilePath
|
|
default:
|
|
return ""
|
|
}
|
|
}
|