refactor: 静态资源哈希算法从 SHA-1 改为 CRC32

- CRC32 更快且语义更匹配缓存破坏场景
- 输出自然为 8 位 hex,无需截取
This commit is contained in:
2026-05-31 02:06:41 +08:00
parent d3e5cbe18b
commit eabceecaae

View File

@ -1,9 +1,8 @@
package common
import (
"crypto/sha1"
"encoding/hex"
"fmt"
"hash/crc32"
"io/fs"
"log"
"net/http"
@ -11,6 +10,7 @@ import (
"os"
"path/filepath"
"regexp"
"strconv"
"sync"
"metazone.cc/metalab/internal/model"
@ -24,7 +24,7 @@ var (
assetOnce sync.Once
)
// ComputeAssetHashes 遍历 static 目录,计算每个文件的 SHA-1 前 8 位作为版本号
// ComputeAssetHashes 遍历 static 目录,计算每个文件的 CRC32作为版本号
func ComputeAssetHashes(templateDir string) {
assetHashes = make(map[string]string)
staticDir := filepath.Join(templateDir, "static")
@ -41,8 +41,8 @@ func ComputeAssetHashes(templateDir string) {
if err != nil {
return nil
}
h := sha1.Sum(data)
shortHash := hex.EncodeToString(h[:])[:8]
h := crc32.ChecksumIEEE(data)
shortHash := strconv.FormatUint(uint64(h), 16)
// 生成 URL 路径:/static/...
rel, _ := filepath.Rel(filepath.Dir(templateDir), path)
urlPath := "/" + filepath.ToSlash(rel)
@ -63,8 +63,8 @@ func ComputeAssetHashes(templateDir string) {
if err != nil {
return nil
}
h := sha1.Sum(data)
shortHash := hex.EncodeToString(h[:])[:8]
h := crc32.ChecksumIEEE(data)
shortHash := strconv.FormatUint(uint64(h), 16)
rel, _ := filepath.Rel(filepath.Dir(templateDir), path)
urlPath := "/" + filepath.ToSlash(rel)
assetHashes[urlPath] = shortHash
@ -84,8 +84,8 @@ func ComputeAssetHashes(templateDir string) {
if err != nil {
return nil
}
h := sha1.Sum(data)
shortHash := hex.EncodeToString(h[:])[:8]
h := crc32.ChecksumIEEE(data)
shortHash := strconv.FormatUint(uint64(h), 16)
rel, _ := filepath.Rel(filepath.Dir(templateDir), path)
urlPath := "/" + filepath.ToSlash(rel)
assetHashes[urlPath] = shortHash