fix(serve): check cover write errors, clean tmp only on failure path (B11)

This commit is contained in:
2026-09-14 19:43:27 +08:00
parent 0c5dfd4353
commit 8023a7ec5c
+10 -5
View File
@@ -2,6 +2,7 @@ package handlers
import (
"fmt"
"log"
"net/http"
"os"
"path"
@@ -60,14 +61,18 @@ func (h *H) ServeCover(c *gin.Context) {
if e == nil {
dst := filepath.Join(dir, "cover"+ext)
if e := os.MkdirAll(dir, 0o755); e == nil {
tmp := fmt.Sprintf("%s.tmp-%d", dst, time.Now().UnixNano()) // 并发幂等:唯一 tmp + rename 原子
if e := os.WriteFile(tmp, img, 0o644); e == nil {
if e := os.Rename(tmp, dst); e == nil {
tmp := fmt.Sprintf("%s.tmp-%d", dst, time.Now().UnixNano())
// B11: check all write errors; clean tmp only on failure.
if we := os.WriteFile(tmp, img, 0o644); we != nil {
log.Printf("serve: write cover tmp: %v", we)
os.Remove(tmp)
} else if re := os.Rename(tmp, dst); re != nil {
log.Printf("serve: rename cover: %v", re)
os.Remove(tmp)
} else {
http.ServeFile(c.Writer, c.Request, dst)
}
}
os.Remove(tmp)
}
}
}
}