[ADD] index.html fallback

This commit is contained in:
sittichok Ouamsiri
2023-07-28 23:14:59 +07:00
parent ddb9307704
commit c83c587d37
+15 -1
View File
@@ -4,10 +4,24 @@ import (
"fmt" "fmt"
"log" "log"
"net/http" "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() { func main() {
fs := http.FileServer(http.Dir("./static")) fs := customFileServer(http.Dir("./static"))
http.Handle("/", fs) http.Handle("/", fs)
fmt.Print("Listening on 4000") fmt.Print("Listening on 4000")
err := http.ListenAndServe(":4000", nil) err := http.ListenAndServe(":4000", nil)