Skip to content

Commit

Permalink
fix: set etag header to cache webUI source
Browse files Browse the repository at this point in the history
  • Loading branch information
garethgeorge committed Nov 17, 2024
1 parent 0ecebf8 commit 0642f4b
Showing 1 changed file with 19 additions and 8 deletions.
27 changes: 19 additions & 8 deletions webui/webui.go
Original file line number Diff line number Diff line change
Expand Up @@ -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, "/") {
Expand Down Expand Up @@ -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))
}

0 comments on commit 0642f4b

Please sign in to comment.