From b733f81ed887fbbda99a6dd521b58a3bf8702d51 Mon Sep 17 00:00:00 2001 From: sakuraiKiyoshi Date: Wed, 7 Jan 2026 14:03:45 +0800 Subject: [PATCH] =?UTF-8?q?fix(=E5=B9=B6=E5=8F=91=E6=8E=A7=E5=88=B6):=20?= =?UTF-8?q?=E4=BF=AE=E5=A4=8Dapps=E6=95=B0=E6=8D=AE=E4=BF=9D=E5=AD=98?= =?UTF-8?q?=E6=97=B6=E7=9A=84=E5=B9=B6=E5=8F=91=E5=AE=89=E5=85=A8=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 将saveApps函数的锁管理移到调用方,确保在文件保存操作期间保持锁 在uploadApp和deleteApp中调整锁的释放时机,防止数据竞争 --- background/main.go | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/background/main.go b/background/main.go index 6e67c8f..0721a57 100644 --- a/background/main.go +++ b/background/main.go @@ -70,11 +70,8 @@ func loadApps() { } } -// 保存apps数据 +// 保存apps数据(调用者需要持有锁) func saveApps() error { - appsMutex.Lock() - defer appsMutex.Unlock() - file, err := os.Create(jsonFile) if err != nil { return fmt.Errorf("failed to create apps.json: %w", err) @@ -129,7 +126,7 @@ func main() { { api.GET("/apps", getApps) api.POST("/apps", uploadApp) - api.DELETE("/apps/:id", deleteApp) // 添加删除应用的API端点 + api.DELETE("/apps/:id", deleteApp) // 添加删除应用的API端点 api.GET("/apps/:id", downloadApp) api.GET("/apps/:id/", downloadApp) // 处理以/结尾的URL api.GET("/docs", getDocs) // 新增获取文档的API端点 @@ -223,13 +220,13 @@ func uploadApp(c *gin.Context) { appsMutex.Lock() apps = append(apps, newApp) - appsMutex.Unlock() - // 保存到文件 if err := saveApps(); err != nil { + appsMutex.Unlock() c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": "保存数据失败: " + err.Error()}) return } + appsMutex.Unlock() c.JSON(http.StatusOK, gin.H{"success": true}) } @@ -308,13 +305,13 @@ func deleteApp(c *gin.Context) { // 从apps切片中删除该应用 appsMutex.Lock() apps = append(apps[:targetIndex], apps[targetIndex+1:]...) - appsMutex.Unlock() - // 保存到文件 if err := saveApps(); err != nil { + appsMutex.Unlock() c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": "保存数据失败: " + err.Error()}) return } + appsMutex.Unlock() c.JSON(http.StatusOK, gin.H{"success": true, "message": "删除成功"}) }