http.FileServer zeigt für Pfade mit Schluss-"/" den Verzeichnisinhalt an; GET /static/media/ listete so alle Uploads samt Vorschau- und Cover-Bildern auf. Beide Dateihandler (assets, static) laufen jetzt über serveFiles, das Verzeichnisse mit 404 beantwortet, und Uploads bekommen wie die Assets ein dauerhaftes Cache-Control (ihre Namen sind einmalig). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
43 lines
1.6 KiB
Go
43 lines
1.6 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
// webDir enthält das gebaute React-Frontend (frontend/ -> npm run build):
|
|
// index.html plus gehashte Dateien unter assets/.
|
|
const webDir = "web"
|
|
|
|
// serveApp liefert die index.html des Frontends; das Routing übernimmt der
|
|
// Client. Nur für die Seitenrouten des Frontends registriert (siehe pageRoutes) --
|
|
// beliebige andere Pfade bleiben ein echtes 404, statt als Seite zu gelten und
|
|
// in der Impression-Statistik zu landen. no-cache, damit nach einem Deploy
|
|
// sofort die neue index.html mit den neuen Asset-Namen geladen wird.
|
|
func serveApp(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Cache-Control", "no-cache")
|
|
http.ServeFile(w, r, webDir+"/index.html")
|
|
}
|
|
|
|
// serveFiles liefert Dateien aus dir mit festem Cache-Control, aber ohne
|
|
// Verzeichnislisting: http.FileServer zeigt sonst für jeden Pfad mit
|
|
// Schluss-"/" den Inhalt des Verzeichnisses -- unter static/media wäre das die
|
|
// Liste aller Uploads.
|
|
func serveFiles(dir, cacheControl string) http.Handler {
|
|
files := http.FileServer(http.Dir(dir))
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
// Leer: StripPrefix hat "/static/" selbst zu "" gemacht, das wäre das
|
|
// Wurzelverzeichnis.
|
|
if r.URL.Path == "" || strings.HasSuffix(r.URL.Path, "/") {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
w.Header().Set("Cache-Control", cacheControl)
|
|
files.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
// immutable ist das Cache-Control für Dateien, deren Name sich mit dem Inhalt
|
|
// ändert: gehashte Assets und Uploads mit zufälligem Namen.
|
|
const immutable = "public, max-age=31536000, immutable"
|