From ad39d8ca23d5e059c259348a4bbdd81e1c92d76b Mon Sep 17 00:00:00 2001 From: Knut Ahlers Date: Sat, 25 Sep 2021 01:50:53 +0200 Subject: [PATCH] Fix: Do not cache index, cache SRI hashes Signed-off-by: Knut Ahlers --- main.go | 14 +------------- tplFuncs.go | 40 ++++++++++++++++++++++++++++++++++++---- 2 files changed, 37 insertions(+), 17 deletions(-) diff --git a/main.go b/main.go index e738d12..2a968db 100644 --- a/main.go +++ b/main.go @@ -1,7 +1,6 @@ package main import ( - "bytes" "embed" "fmt" "mime" @@ -27,8 +26,6 @@ var ( VersionAndExit bool `flag:"version" default:"false" description:"Print version information and exit"` } - cachedIndex []byte - product = "ots" version = "dev" ) @@ -93,11 +90,6 @@ func assetDelivery(w http.ResponseWriter, r *http.Request) { } func handleIndex(w http.ResponseWriter, r *http.Request) { - if cachedIndex != nil { - w.Write(cachedIndex) - return - } - indexTpl, err := assets.ReadFile("frontend/index.html") if err != nil { http.Error(w, "404 not found", http.StatusNotFound) @@ -110,14 +102,10 @@ func handleIndex(w http.ResponseWriter, r *http.Request) { return } - buf := new(bytes.Buffer) - if err = tpl.Execute(buf, struct{ Vars map[string]string }{Vars: getJSVars(r)}); err != nil { + if err = tpl.Execute(w, struct{ Vars map[string]string }{Vars: getJSVars(r)}); err != nil { http.Error(w, errors.Wrap(err, "parsing template").Error(), http.StatusInternalServerError) return } - - cachedIndex = buf.Bytes() - w.Write(buf.Bytes()) } func getJSVars(r *http.Request) map[string]string { diff --git a/tplFuncs.go b/tplFuncs.go index 4d7c7a5..6e6fb91 100644 --- a/tplFuncs.go +++ b/tplFuncs.go @@ -4,14 +4,22 @@ import ( "crypto/sha512" "encoding/base64" "path" + "sync" "text/template" ) -var tplFuncs = template.FuncMap{ - "SRIHash": assetSRIHash, -} +var ( + sriCacheStore = newSRICache() + tplFuncs = template.FuncMap{ + "SRIHash": assetSRIHash, + } +) func assetSRIHash(assetName string) string { + if sri, ok := sriCacheStore.Get(assetName); ok { + return sri + } + data, err := assets.ReadFile(path.Join("frontend", assetName)) if err != nil { panic(err) @@ -21,5 +29,29 @@ func assetSRIHash(assetName string) string { h.Write(data) sum := h.Sum(nil) - return "sha384-" + base64.StdEncoding.EncodeToString(sum) + sri := "sha384-" + base64.StdEncoding.EncodeToString(sum) + sriCacheStore.Set(assetName, sri) + return sri +} + +type sriCache struct { + c map[string]string + l sync.RWMutex +} + +func newSRICache() *sriCache { return &sriCache{c: map[string]string{}} } + +func (s *sriCache) Get(assetName string) (string, bool) { + s.l.RLock() + defer s.l.RUnlock() + + h, ok := s.c[assetName] + return h, ok +} + +func (s *sriCache) Set(assetName, hash string) { + s.l.Lock() + defer s.l.Unlock() + + s.c[assetName] = hash }