From 21e5406e96dea0e2e3a971f18a799e76f8d7bb0c Mon Sep 17 00:00:00 2001 From: Vasiliy Tolstov Date: Sat, 7 Dec 2024 01:20:47 +0300 Subject: [PATCH] add spa handler Signed-off-by: Vasiliy Tolstov --- handler/spa/spa.go | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 handler/spa/spa.go diff --git a/handler/spa/spa.go b/handler/spa/spa.go new file mode 100644 index 0000000..ac389a8 --- /dev/null +++ b/handler/spa/spa.go @@ -0,0 +1,19 @@ +package spa + +import ( + "io/fs" + "net/http" + "strings" +) + +// Handler serve files from dir and redirect to index if file not exists +var Handler = func(prefix string, dir fs.FS) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + f := http.StripPrefix(prefix, http.FileServer(http.FS(dir))) + if _, err := fs.Stat(dir, strings.TrimPrefix(r.RequestURI, prefix)); err != nil { + r.RequestURI = prefix + r.URL.Path = prefix + } + f.ServeHTTP(w, r) + } +}