From 06495fa358902cfcfd5beb0ae584a3554a39935e Mon Sep 17 00:00:00 2001 From: Maximilian Friedersdorff Date: Fri, 27 Jun 2025 20:39:17 +0100 Subject: [PATCH] Add caching to static files based on etag --- cmd/server/main.go | 14 +++++++++++++- internal/middleware/etag_cache.go | 21 +++------------------ 2 files changed, 16 insertions(+), 19 deletions(-) diff --git a/cmd/server/main.go b/cmd/server/main.go index 8435b13..31342ee 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -6,8 +6,10 @@ import ( "net" "net/http" "os" + "time" "forgejo.gwairfelin.com/max/gonotes/internal/conf" + "forgejo.gwairfelin.com/max/gonotes/internal/middleware" "forgejo.gwairfelin.com/max/gonotes/internal/notes/views" ) @@ -24,12 +26,22 @@ func main() { router := http.NewServeMux() notesRouter := views.GetRoutes("/notes") + cacheExpiration, err := time.ParseDuration("24h") + if err != nil { + log.Fatal(err) + } + + etag := middleware.NewETag("static", cacheExpiration) + router.Handle("/", logger(http.RedirectHandler("/notes/", http.StatusFound))) router.Handle("/notes/", logger(http.StripPrefix("/notes", notesRouter))) router.Handle( "/static/", logger( - http.FileServer(http.FS(conf.Static)), + middleware.StaticEtagMiddleware( + *etag, + http.FileServer(http.FS(conf.Static)), + ), ), ) diff --git a/internal/middleware/etag_cache.go b/internal/middleware/etag_cache.go index d19cfbe..d1878c2 100644 --- a/internal/middleware/etag_cache.go +++ b/internal/middleware/etag_cache.go @@ -2,7 +2,6 @@ package middleware import ( "fmt" - "hash/crc64" "log" "net/http" "strings" @@ -13,11 +12,8 @@ type ETag struct { Name string Value string Expiration time.Duration - HashTime time.Duration } -var etags = make([]*ETag, 0) - func (etag *ETag) Header() string { return fmt.Sprintf("\"pb-%s-%s\"", etag.Name, etag.Value) } @@ -46,21 +42,10 @@ func StaticEtagMiddleware(etag ETag, next http.Handler) http.Handler { } // GenerateETagFromBuffer calculates etag value from one or more buffers (e.g. embedded files) -func GenerateETagFromBuffer(name string, expiration time.Duration, buffers ...[]byte) (*ETag, error) { - start := time.Now() - hash := crc64.New(crc64.MakeTable(crc64.ECMA)) - for _, buffer := range buffers { - _, err := hash.Write(buffer) - if err != nil { - return nil, fmt.Errorf("unable to generate etag from buffer: %w", err) - } - } - etag := &ETag{ +func NewETag(name string, expiration time.Duration) *ETag { + return &ETag{ Name: name, Expiration: expiration, - Value: fmt.Sprintf("%x", hash.Sum64()), - HashTime: time.Since(start), + Value: fmt.Sprintf("%d", time.Now().Unix()), } - etags = append(etags, etag) - return etag, nil }