调整项目结构,factory只负责暴露方法,不实现业务细节

This commit is contained in:
2025-12-07 00:04:01 +08:00
parent b66f345281
commit 339920a940
23 changed files with 2165 additions and 1231 deletions

View File

@@ -7,7 +7,6 @@ import (
"time"
"git.toowon.com/jimmy/go-common/factory"
commonhttp "git.toowon.com/jimmy/go-common/http"
)
// 示例Factory黑盒模式 - 最简化的使用方式
@@ -44,8 +43,6 @@ func main() {
// 用户列表
func handleUsers(w http.ResponseWriter, r *http.Request) {
h := commonhttp.NewHandler(w, r)
// 创建工厂(在处理器中也可以复用)
fac, _ := factory.NewFactoryFromFile("config.json")
ctx := context.Background()
@@ -59,7 +56,7 @@ func handleUsers(w http.ResponseWriter, r *http.Request) {
cacheKey := "users:list"
cached, _ := fac.RedisGet(ctx, cacheKey)
if cached != "" {
h.Success(cached)
fac.Success(w, cached)
return
}
@@ -72,12 +69,11 @@ func handleUsers(w http.ResponseWriter, r *http.Request) {
// 4. 缓存结果
fac.RedisSet(ctx, cacheKey, users, 5*time.Minute)
h.Success(users)
fac.Success(w, users)
}
// 文件上传
func handleUpload(w http.ResponseWriter, r *http.Request) {
h := commonhttp.NewHandler(w, r)
fac, _ := factory.NewFactoryFromFile("config.json")
ctx := context.Background()
@@ -85,7 +81,7 @@ func handleUpload(w http.ResponseWriter, r *http.Request) {
file, header, err := r.FormFile("file")
if err != nil {
fac.LogError("文件上传失败: %v", err)
h.Error(400, "文件上传失败")
fac.Error(w, 400, "文件上传失败")
return
}
defer file.Close()
@@ -95,7 +91,7 @@ func handleUpload(w http.ResponseWriter, r *http.Request) {
url, err := fac.UploadFile(ctx, objectKey, file, header.Header.Get("Content-Type"))
if err != nil {
fac.LogError("文件上传到存储失败: %v", err)
h.Error(500, "文件上传失败")
fac.Error(w, 500, "文件上传失败")
return
}
@@ -106,7 +102,7 @@ func handleUpload(w http.ResponseWriter, r *http.Request) {
"url": url,
}, "文件上传成功")
h.Success(map[string]interface{}{
fac.Success(w, map[string]interface{}{
"url": url,
})
}
@@ -122,16 +118,14 @@ func authMiddleware(next http.Handler) http.Handler {
// 获取token
token := r.Header.Get("Authorization")
if token == "" {
h := commonhttp.NewHandler(w, r)
h.Error(401, "未授权")
fac.Error(w, 401, "未授权")
return
}
// 从Redis验证token黑盒方法
userID, err := fac.RedisGet(ctx, "token:"+token)
if err != nil || userID == "" {
h := commonhttp.NewHandler(w, r)
h.Error(401, "token无效")
fac.Error(w, 401, "token无效")
return
}