refactor(utils): add unified ETag generation function

Extract duplicate generateETag function from handler/static.go and
cache/file_cache.go into internal/utils/etag.go. Both functions were
identical, using strconv.AppendInt for zero-allocation ETag generation.

- Create utils.GenerateETag(modTime, size) as the unified implementation
- Update handler/static.go to call utils.GenerateETag
- Update cache/file_cache.go to call utils.GenerateETag
- Remove unused strconv import from static.go

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
xfy 2026-05-08 18:06:13 +08:00
parent 8c96c4384f
commit 3b2360162c
3 changed files with 24 additions and 18 deletions

View File

@ -20,11 +20,12 @@ package cache
import (
"container/list"
"slices"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"rua.plus/lolly/internal/utils"
)
// FileEntry 文件缓存条目,存储单个文件的缓存信息。
@ -43,14 +44,7 @@ type FileEntry struct {
// generateETag 基于 ModTime 和 Size 生成 ETag。
// 使用 strconv.AppendInt 避免 fmt.Sprintf 分配。
func generateETag(modTime time.Time, size int64) string {
var buf [32]byte
b := buf[:0]
b = append(b, '"')
b = strconv.AppendInt(b, modTime.Unix(), 16)
b = append(b, '-')
b = strconv.AppendInt(b, size, 16)
b = append(b, '"')
return string(b)
return utils.GenerateETag(modTime, size)
}
// FileCache 文件缓存,支持 LRU 淘汰策略。

View File

@ -22,7 +22,6 @@ import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"time"
@ -913,14 +912,7 @@ func (h *StaticHandler) validateSymlink(filePath string) error {
// generateETag 基于 ModTime 和 Size 生成 ETag。
// 使用 strconv.AppendInt 避免 fmt.Sprintf 分配。
func generateETag(modTime time.Time, size int64) string {
var buf [32]byte
b := buf[:0]
b = append(b, '"')
b = strconv.AppendInt(b, modTime.Unix(), 16)
b = append(b, '-')
b = strconv.AppendInt(b, size, 16)
b = append(b, '"')
return string(b)
return utils.GenerateETag(modTime, size)
}
// isNotModified 检查条件请求是否匹配(返回 true 表示应返回 304

20
internal/utils/etag.go Normal file
View File

@ -0,0 +1,20 @@
package utils
import (
"strconv"
"time"
)
// GenerateETag 基于 ModTime 和 Size 生成 ETag。
// 使用 strconv.AppendInt 避免 fmt.Sprintf 分配。
// 格式: "<modtime-unix-hex>-<size-hex>"
func GenerateETag(modTime time.Time, size int64) string {
var buf [32]byte
b := buf[:0]
b = append(b, '"')
b = strconv.AppendInt(b, modTime.Unix(), 16)
b = append(b, '-')
b = strconv.AppendInt(b, size, 16)
b = append(b, '"')
return string(b)
}