From e78b4ce25ffcf1de0de3e4883daf97b65ab821df Mon Sep 17 00:00:00 2001 From: meskio <meskio@sindominio.net> Date: Tue, 29 Sep 2020 17:32:26 +0200 Subject: [PATCH] Serve properly a single page app --- main.go | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/main.go b/main.go index a42b991..6b10f95 100644 --- a/main.go +++ b/main.go @@ -4,12 +4,38 @@ import ( "flag" "log" "net/http" + "os" + "path/filepath" "0xacab.org/meskio/cicer/api" "github.com/gorilla/mux" "github.com/olivere/env" ) +type handler struct { + assets string +} + +func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + path, err := filepath.Abs(r.URL.Path) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + path = filepath.Join(h.assets, path) + _, err = os.Stat(path) + if os.IsNotExist(err) { + http.ServeFile(w, r, h.assets) + return + } else if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + http.FileServer(http.Dir(h.assets)).ServeHTTP(w, r) +} + func main() { var ( dbPath = flag.String("db-path", env.String("./test.db", "DB_PATH"), "Path where the sqlite will be located {DB_PATH}") @@ -28,6 +54,7 @@ func main() { } log.Println("assets:", *assets) - r.PathPrefix("/").Handler(http.FileServer(http.Dir(*assets))) + h := handler{*assets} + r.PathPrefix("/").Handler(h) log.Fatal(http.ListenAndServe(*addr, r)) } -- GitLab