Fix Navigation when reloading on a virtual path (#1000)
Signed-off-by: Daniel Valdivia <18384552+dvaldivia@users.noreply.github.com>
This commit is contained in:
@@ -25,6 +25,7 @@ import (
|
||||
"io/fs"
|
||||
"log"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -234,14 +235,31 @@ func (w *notFoundRedirectRespWr) Write(p []byte) (int, error) {
|
||||
return len(p), nil // Lie that we successfully wrote it
|
||||
}
|
||||
|
||||
var reHrefIndex = regexp.MustCompile(`(?m)((href|src)="(.\/).*?")`)
|
||||
|
||||
// wrapHandlerSinglePageApplication handles a http.FileServer returning a 404 and overrides it with index.html
|
||||
func wrapHandlerSinglePageApplication(h http.Handler) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
nfrw := ¬FoundRedirectRespWr{ResponseWriter: w}
|
||||
h.ServeHTTP(nfrw, r)
|
||||
if nfrw.status == 404 {
|
||||
if nfrw.status == 404 || r.URL.String() == "/" {
|
||||
basePath := "/"
|
||||
// For SPA mode we will replace relative paths with absolute unless we receive query param cp=y
|
||||
if val, ok := r.URL.Query()["cp"]; ok && len(val) > 0 && val[0] == "y" {
|
||||
basePath = "./"
|
||||
}
|
||||
|
||||
indexPage, _ := portal_ui.GetStaticAssets().Open("build/index.html")
|
||||
indexPageBytes, _ := io.ReadAll(indexPage)
|
||||
if basePath != "./" {
|
||||
indexPageStr := string(indexPageBytes)
|
||||
for _, match := range reHrefIndex.FindAllStringSubmatch(indexPageStr, -1) {
|
||||
toReplace := strings.Replace(match[1], match[3], basePath, 1)
|
||||
indexPageStr = strings.Replace(indexPageStr, match[1], toReplace, 1)
|
||||
}
|
||||
indexPageBytes = []byte(indexPageStr)
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
http.ServeContent(w, r, "index.html", time.Now(), bytes.NewReader(indexPageBytes))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user