2021-05-02 12:29:43 +00:00
|
|
|
// FROM https://gist.github.com/lummie/91cd1c18b2e32fa9f316862221a6fd5c
|
|
|
|
|
2023-05-31 12:49:45 +00:00
|
|
|
package webserver
|
2021-05-02 12:29:43 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"os"
|
|
|
|
"path"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
func FileServerWithDefault(root http.FileSystem) http.Handler {
|
|
|
|
fs := http.FileServer(root)
|
|
|
|
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
2023-05-31 12:49:45 +00:00
|
|
|
// make sure the url path starts with /
|
2021-05-02 12:29:43 +00:00
|
|
|
upath := r.URL.Path
|
|
|
|
if !strings.HasPrefix(upath, "/") {
|
|
|
|
upath = "/" + upath
|
|
|
|
r.URL.Path = upath
|
|
|
|
}
|
|
|
|
upath = path.Clean(upath)
|
|
|
|
|
|
|
|
// attempt to open the file via the http.FileSystem
|
|
|
|
f, err := root.Open(upath)
|
|
|
|
if err != nil {
|
|
|
|
if os.IsNotExist(err) {
|
|
|
|
// Revert to homepage
|
|
|
|
r.URL.Path = "/"
|
|
|
|
}
|
2021-10-28 09:01:52 +00:00
|
|
|
} else {
|
|
|
|
// close if successfully opened
|
|
|
|
_ = f.Close()
|
2021-05-02 12:29:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// default serve
|
|
|
|
fs.ServeHTTP(w, r)
|
|
|
|
})
|
|
|
|
}
|