mirror of
https://github.com/garethgeorge/backrest.git
synced 2025-12-17 02:55:39 +00:00
fix: set etag header to cache webUI source
This commit is contained in:
@@ -2,12 +2,29 @@ package webui
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"crypto/md5"
|
||||||
|
"encoding/hex"
|
||||||
"io"
|
"io"
|
||||||
"io/fs"
|
"io/fs"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"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 {
|
func Handler() http.Handler {
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
if strings.HasSuffix(r.URL.Path, "/") {
|
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)
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
w.Header().Set("ETag", calcEtag(path, data))
|
||||||
stat, err := f.Stat()
|
http.ServeContent(w, r, path, time.Time{}, bytes.NewReader(data))
|
||||||
if err != nil {
|
|
||||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
http.ServeContent(w, r, path, stat.ModTime(), bytes.NewReader(data))
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user