2023-03-01 14:39:36 +01:00
|
|
|
package http
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"os"
|
|
|
|
"path"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
"gitlab.com/wpetit/goweb/logger"
|
|
|
|
)
|
|
|
|
|
|
|
|
func HTML5Fileserver(fs http.FileSystem) http.Handler {
|
|
|
|
handler := http.FileServer(fs)
|
|
|
|
|
|
|
|
fn := func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
urlPath := r.URL.Path
|
|
|
|
if !strings.HasPrefix(urlPath, "/") {
|
|
|
|
urlPath = "/" + urlPath
|
|
|
|
r.URL.Path = urlPath
|
|
|
|
}
|
|
|
|
urlPath = path.Clean(urlPath)
|
|
|
|
|
|
|
|
file, err := fs.Open(urlPath)
|
|
|
|
if err != nil {
|
|
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
|
|
r.URL.Path = "/"
|
|
|
|
|
|
|
|
handler.ServeHTTP(w, r)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-10-19 21:47:09 +02:00
|
|
|
logger.Error(r.Context(), "could not open bundle file", logger.CapturedE(err))
|
2023-03-01 14:39:36 +01:00
|
|
|
|
|
|
|
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
defer func() {
|
|
|
|
if err := file.Close(); err != nil {
|
2023-10-19 21:47:09 +02:00
|
|
|
logger.Error(r.Context(), "could not close file", logger.CapturedE(err))
|
2023-03-01 14:39:36 +01:00
|
|
|
|
|
|
|
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
handler.ServeHTTP(w, r)
|
|
|
|
}
|
|
|
|
|
|
|
|
return http.HandlerFunc(fn)
|
|
|
|
}
|