Improve caching

This commit is contained in:
2026-09-28 22:19:17 +02:00
parent 3070471c38
commit 65ce1b414e
15 changed files with 236 additions and 67 deletions
+8 -33
View File
@@ -2,12 +2,9 @@ package main
import (
"context"
"crypto/sha256"
"embed"
"encoding/hex"
"flag"
"html/template"
"io/fs"
"log"
"net/http"
"net/url"
@@ -23,29 +20,14 @@ import (
//go:embed assets
var assets embed.FS
// editorBundleVersion is a short content hash of the vendored CodeMirror bundle,
// appended as ?v=… to its <script> src. The bundle is served immutable under a
// stable filename, so without this query a rebuilt bundle would never reach a
// client that already cached the old one (this is the editor cache-bust knob).
var editorBundleVersion = hashAsset("assets/editor/vendor/codemirror.bundle.js")
func hashAsset(name string) string {
b, err := assets.ReadFile(name)
if err != nil {
return ""
}
sum := sha256.Sum256(b)
return hex.EncodeToString(sum[:])[:12]
}
// tmplFuncs is shared by every layout-based template: the edit template appends
// editorBundleVersion to its CodeMirror <script> src to cache-bust the bundle;
// the layout header renders the maintenance widget.
// tmplFuncs is shared by every layout-based template: asset links versioned
// static files (see static.go); the layout header renders the maintenance
// widget.
var tmplFuncs = template.FuncMap{
"editorBundleVersion": func() string { return editorBundleVersion },
"fileIcon": fileIcon,
"icon": readIcon,
"maintenanceWidget": maintenanceWidget,
"asset": assetURL,
"fileIcon": fileIcon,
"icon": readIcon,
"maintenanceWidget": maintenanceWidget,
}
var (
@@ -137,14 +119,7 @@ func main() {
}
h := &handler{root: root, user: *user, pass: *pass, authKey: authKey}
staticFS, _ := fs.Sub(assets, "assets")
static := http.StripPrefix("/_/", http.FileServer(http.FS(staticFS)))
http.Handle("/_/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/_/fonts/") || strings.HasPrefix(r.URL.Path, "/_/editor/vendor/") {
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
}
static.ServeHTTP(w, r)
}))
http.Handle("/_/", serveStatic())
http.HandleFunc("/_logout", h.handleLogout)
http.HandleFunc("/_reindex", h.handleReindex)
http.HandleFunc("/_search", h.handleSearchSuggest)