Fix: Do not cache index, cache SRI hashes

Signed-off-by: Knut Ahlers <knut@ahlers.me>
This commit is contained in:
Knut Ahlers 2021-09-25 01:50:53 +02:00
parent e5a661e6aa
commit ad39d8ca23
No known key found for this signature in database
GPG Key ID: 0066F03ED215AD7D
2 changed files with 37 additions and 17 deletions

14
main.go
View File

@ -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 {

View File

@ -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
}