fix: 添加互斥锁以避免并发请求导致的构建或重启冲突

This commit is contained in:
lixiangwuxian 2025-05-03 23:37:28 +08:00
parent 40a336af36
commit d4038a568e

View File

@ -6,6 +6,7 @@ import (
"net/http" "net/http"
"os" "os"
"os/exec" "os/exec"
"sync"
"time" "time"
"git.lxtend.com/qqbot/config" "git.lxtend.com/qqbot/config"
@ -19,6 +20,9 @@ import (
var hasVaildBuild = true var hasVaildBuild = true
// 避免被并发请求构建或重启
var stuffMutex sync.Mutex
func init() { func init() {
handler.RegisterHandler("/重启bot", restart, constants.LEVEL_ADMIN) handler.RegisterHandler("/重启bot", restart, constants.LEVEL_ADMIN)
handler.RegisterHelpInform("/重启bot", "热更新", "重启bot") handler.RegisterHelpInform("/重启bot", "热更新", "重启bot")
@ -169,6 +173,8 @@ func buildBot() error {
} }
func PullCodeHandler(c *gin.Context) { func PullCodeHandler(c *gin.Context) {
stuffMutex.Lock()
defer stuffMutex.Unlock()
err := util.GitPull() err := util.GitPull()
log.Println("拉取代码...") log.Println("拉取代码...")
if err != nil { if err != nil {
@ -180,6 +186,8 @@ func PullCodeHandler(c *gin.Context) {
} }
func BuildBotHandler(c *gin.Context) { func BuildBotHandler(c *gin.Context) {
stuffMutex.Lock()
defer stuffMutex.Unlock()
err := buildBot() err := buildBot()
log.Println("构建程序...") log.Println("构建程序...")
if err != nil { if err != nil {
@ -196,6 +204,8 @@ func RestartBotHandler(c *gin.Context) {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"}) c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
return return
} }
stuffMutex.Lock()
defer stuffMutex.Unlock()
err := restartProgram() err := restartProgram()
log.Println("重启程序...") log.Println("重启程序...")
if err != nil { if err != nil {