From b16713de56739137dff68ce2800cd35d3962240e Mon Sep 17 00:00:00 2001 From: BuckarooBanzay Date: Sat, 19 Mar 2022 17:23:18 +0100 Subject: [PATCH] improved static file handling and caching --- web/cachedfs.go | 24 ++++++++++++++++++++++++ web/serve.go | 11 ++++++++++- 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 web/cachedfs.go diff --git a/web/cachedfs.go b/web/cachedfs.go new file mode 100644 index 0000000..6ca8ecb --- /dev/null +++ b/web/cachedfs.go @@ -0,0 +1,24 @@ +package web + +import ( + "fmt" + "net/http" + "strings" + "time" +) + +func CachedServeFunc(h http.HandlerFunc) http.HandlerFunc { + var etag = fmt.Sprintf(`"%d"`, time.Now().UnixMicro()) + return func(w http.ResponseWriter, r *http.Request) { + if match := r.Header.Get("If-None-Match"); match != "" { + if strings.Contains(match, etag) { + w.WriteHeader(http.StatusNotModified) + return + } + } + + w.Header().Set("Cache-Control", "max-age=60") + w.Header().Set("ETag", etag) + h.ServeHTTP(w, r) + } +} diff --git a/web/serve.go b/web/serve.go index ed28ad4..8dde681 100644 --- a/web/serve.go +++ b/web/serve.go @@ -23,7 +23,16 @@ func Serve(ctx *app.App) { mux := http.NewServeMux() // static files - mux.Handle("/", http.FileServer(getFileSystem(ctx.Config.Webdev, public.Files))) + if ctx.Config.Webdev { + logrus.Print("using live mode") + fs := http.FileServer(http.FS(os.DirFS("public"))) + mux.HandleFunc("/", fs.ServeHTTP) + + } else { + logrus.Print("using embed mode") + fs := http.FileServer(http.FS(public.Files)) + mux.HandleFunc("/", CachedServeFunc(fs.ServeHTTP)) + } tiles := &Tiles{ctx: ctx} tiles.Init()