about summary refs log tree commit diff stats
path: root/frontend/assets.go
diff options
context:
space:
mode:
authorAlan Pearce2024-06-03 22:24:39 +0200
committerAlan Pearce2024-06-03 22:24:39 +0200
commit872ae5db32c605ef385588a33673ce5fef29ff21 (patch)
treec454f8d32cd4554c4780a50bb43ae7e9f82688cd /frontend/assets.go
parent896926a63a8f2d145467b325f9b0198315e0af6d (diff)
downloadsearchix-872ae5db32c605ef385588a33673ce5fef29ff21.tar.lz
searchix-872ae5db32c605ef385588a33673ce5fef29ff21.tar.zst
searchix-872ae5db32c605ef385588a33673ce5fef29ff21.zip
feat: use stale-while-revalidate instead of immutable asset paths
Diffstat (limited to 'frontend/assets.go')
-rw-r--r--frontend/assets.go30
1 files changed, 12 insertions, 18 deletions
diff --git a/frontend/assets.go b/frontend/assets.go
index c04e706..46369fa 100644
--- a/frontend/assets.go
+++ b/frontend/assets.go
@@ -3,32 +3,31 @@ package frontend
 import (
 	"crypto/sha256"
 	"encoding/base64"
-	"encoding/hex"
+	"fmt"
 	"hash/fnv"
 	"io"
 	"io/fs"
-	"path/filepath"
-	"strings"
 
 	"github.com/pkg/errors"
 )
 
 var Assets = &AssetCollection{
-	Scripts:         make(map[string]*Asset),
-	Stylesheets:     make(map[string]*Asset),
-	ByImmutablePath: make(map[string]*Asset),
+	Scripts:     make(map[string]*Asset),
+	Stylesheets: make(map[string]*Asset),
+	ByPath:      make(map[string]*Asset),
 }
 
 type Asset struct {
 	URL          string
+	ETag         string
 	Filename     string
 	Base64SHA256 string
 }
 
 type AssetCollection struct {
-	Scripts         map[string]*Asset
-	Stylesheets     map[string]*Asset
-	ByImmutablePath map[string]*Asset
+	Scripts     map[string]*Asset
+	Stylesheets map[string]*Asset
+	ByPath      map[string]*Asset
 }
 
 func newAsset(filename string) (*Asset, error) {
@@ -45,18 +44,13 @@ func newAsset(filename string) (*Asset, error) {
 	}
 
 	return &Asset{
-		URL:          makeImmutablePath(filename, hex.EncodeToString(hash.Sum(nil))),
+		URL:          "/" + filename,
+		ETag:         fmt.Sprintf(`W/"%x"`, hash.Sum(nil)),
 		Filename:     filename,
 		Base64SHA256: base64.StdEncoding.EncodeToString(shasum.Sum(nil)),
 	}, nil
 }
 
-func makeImmutablePath(filename string, hash string) string {
-	ext := filepath.Ext(filename)
-
-	return "/" + strings.Replace(filename, ext, "."+hash+ext, 1)
-}
-
 func hashScripts() error {
 	scripts, err := fs.Glob(Files, "static/**.js")
 	if err != nil {
@@ -68,7 +62,7 @@ func hashScripts() error {
 			return err
 		}
 		Assets.Scripts[filename] = asset
-		Assets.ByImmutablePath[asset.URL] = asset
+		Assets.ByPath[asset.URL] = asset
 	}
 
 	return nil
@@ -85,7 +79,7 @@ func hashStyles() error {
 			return err
 		}
 		Assets.Stylesheets[filename] = asset
-		Assets.ByImmutablePath[asset.URL] = asset
+		Assets.ByPath[asset.URL] = asset
 	}
 
 	return nil