mirror of
https://github.com/ThisTine/simple-http-server.git
synced 2026-08-18 23:18:48 +07:00
[ADD] index.html fallback
This commit is contained in:
@@ -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)
|
||||||
|
|||||||
Reference in New Issue
Block a user