Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions modules/caddyhttp/fileserver/calculate_etag_bench_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package fileserver

import (
"io/fs"
"testing"
"time"
)

type benchFileInfo struct {
size int64
mtime time.Time
}

func (fi benchFileInfo) Name() string { return "file.txt" }
func (fi benchFileInfo) Size() int64 { return fi.size }
func (fi benchFileInfo) Mode() fs.FileMode { return 0o644 }
func (fi benchFileInfo) ModTime() time.Time { return fi.mtime }
func (fi benchFileInfo) IsDir() bool { return false }
func (fi benchFileInfo) Sys() any { return nil }

func BenchmarkCalculateEtag(b *testing.B) {
fi := benchFileInfo{size: 1234567, mtime: time.Unix(1700000000, 123456789)}
b.ReportAllocs()
for b.Loop() {
_ = calculateEtag(fi)
}
}
14 changes: 8 additions & 6 deletions modules/caddyhttp/fileserver/staticfiles.go
Original file line number Diff line number Diff line change
Expand Up @@ -765,12 +765,14 @@ func calculateEtag(d os.FileInfo) string {
if !usefulModTime(mtime) {
return ""
}
var sb strings.Builder
sb.WriteRune('"')
sb.WriteString(strconv.FormatInt(mtime.UnixNano(), 36))
sb.WriteString(strconv.FormatInt(d.Size(), 36))
sb.WriteRune('"')
return sb.String()
// A quoted etag of two base-36 int64 values is 30 bytes, thus fitting
// comfortably in 32 bytes, on the stack to prevent allocations
var buf [32]byte
b := append(buf[:0], '"')
b = strconv.AppendInt(b, mtime.UnixNano(), 36)
b = strconv.AppendInt(b, d.Size(), 36)
b = append(b, '"')
return string(b)
}

// Finds the first corresponding etag file for a given file in the file system and return its content
Expand Down