From c83c587d37fc9874a114d521d843734826169572 Mon Sep 17 00:00:00 2001 From: sittichok Ouamsiri Date: Fri, 28 Jul 2023 23:14:59 +0700 Subject: [PATCH] [ADD] index.html fallback --- main.go | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/main.go b/main.go index f69ce27..9ac6afe 100644 --- a/main.go +++ b/main.go @@ -4,10 +4,24 @@ import ( "fmt" "log" "net/http" + "os" + "path" ) +func customFileServer(fs http.FileSystem) http.Handler { + fileServer := http.FileServer(fs) + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, err := fs.Open(path.Clean(r.URL.Path)) // Do not allow path traversals. + if os.IsNotExist(err) { + http.ServeFile(w, r, "./static/index.html") + return + } + fileServer.ServeHTTP(w, r) + }) +} + func main() { - fs := http.FileServer(http.Dir("./static")) + fs := customFileServer(http.Dir("./static")) http.Handle("/", fs) fmt.Print("Listening on 4000") err := http.ListenAndServe(":4000", nil)