From 93dfe2be64e8658839bcfe5356adf35f8cde7075 Mon Sep 17 00:00:00 2001 From: Nicolas James Date: Thu, 13 Feb 2025 18:04:18 +1100 Subject: initial commit --- src/server/spa.go | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/server/spa.go (limited to 'src/server/spa.go') diff --git a/src/server/spa.go b/src/server/spa.go new file mode 100644 index 0000000..1dd1e96 --- /dev/null +++ b/src/server/spa.go @@ -0,0 +1,37 @@ +package main + +import ( + "net/http" + "os" + "path/filepath" +) + +// https://github.com/gorilla/mux#serving-single-page-applications +type spaHandler struct { + staticPath string +} + +func (h spaHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) { + path, err := filepath.Abs(request.URL.Path) + if err != nil { + http.Error(writer, err.Error(), http.StatusBadRequest) + } + + path = filepath.Join(h.staticPath, path) + if _, err = os.Stat(path); os.IsNotExist(err) { + + serve_path := filepath.Base(path) + if len(filepath.Ext(path)) == 0 { + serve_path = "index.html" + } + serve_path = filepath.Join(h.staticPath, serve_path) + + http.ServeFile(writer, request, serve_path) + return + } else if err != nil { + http.Error(writer, err.Error(), http.StatusInternalServerError) + return + } + + http.FileServer(http.Dir(h.staticPath)).ServeHTTP(writer, request) +} -- cgit v1.2.3