Merge pull request 'handler: add single page application handler' (#176) from spa-handler into master

Reviewed-on: #176
This commit is contained in:
Василий Толстов 2023-08-19 23:22:00 +03:00
commit 41f7bdf182
1 changed files with 19 additions and 0 deletions

19
handler/spa/spa.go Normal file
View File

@ -0,0 +1,19 @@
package spa
import (
"io/fs"
"net/http"
"strings"
)
// Handler serve files from dir and redirect to index if file not exists
var Handler = func(prefix string, dir fs.FS) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
f := http.StripPrefix(prefix, http.FileServer(http.FS(dir)))
if _, err := fs.Stat(dir, strings.TrimPrefix(r.RequestURI, prefix)); err != nil {
r.RequestURI = prefix
r.URL.Path = prefix
}
f.ServeHTTP(w, r)
}
}