From 0642f4b65a11daab379708d7ed813ca8d6a2140f Mon Sep 17 00:00:00 2001 From: garethgeorge Date: Sun, 17 Nov 2024 00:36:42 -0800 Subject: [PATCH] fix: set etag header to cache webUI source --- webui/webui.go | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/webui/webui.go b/webui/webui.go index bebf962c7..0092a5b88 100644 --- a/webui/webui.go +++ b/webui/webui.go @@ -2,12 +2,29 @@ package webui import ( "bytes" + "crypto/md5" + "encoding/hex" "io" "io/fs" "net/http" "strings" + "time" ) +var etagCache = make(map[string]string) + +func calcEtag(path string, data []byte) string { + etag, ok := etagCache[path] + if ok { + return etag + } + + md5sum := md5.Sum(data) + etag = "\"" + hex.EncodeToString(md5sum[:]) + "\"" + etagCache[path] = etag + return etag +} + func Handler() http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if strings.HasSuffix(r.URL.Path, "/") { @@ -39,12 +56,6 @@ func serveFile(f fs.File, w http.ResponseWriter, r *http.Request, path string) { http.Error(w, err.Error(), http.StatusInternalServerError) return } - - stat, err := f.Stat() - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - - http.ServeContent(w, r, path, stat.ModTime(), bytes.NewReader(data)) + w.Header().Set("ETag", calcEtag(path, data)) + http.ServeContent(w, r, path, time.Time{}, bytes.NewReader(data)) }