rotas no back
This commit is contained in:
@@ -78,18 +78,59 @@ func main() {
|
||||
http.ServeFile(w, r, filepath.Join(webDir, "index.html"))
|
||||
})
|
||||
r.Get(base+"/*", func(w http.ResponseWriter, r *http.Request) {
|
||||
// strip base path
|
||||
// O BASE_PATH é apenas o prefixo público: /initpage/apps/ aponta para
|
||||
// /app/web/apps/, sem repetir "initpage" dentro da pasta web.
|
||||
p := strings.TrimPrefix(r.URL.Path, base)
|
||||
if p == "" {
|
||||
p = "/"
|
||||
rel := filepath.Clean(filepath.FromSlash(strings.TrimPrefix(p, "/")))
|
||||
serveIndex := func(indexPath string) bool {
|
||||
st, err := os.Stat(indexPath)
|
||||
if err != nil || st.IsDir() {
|
||||
return false
|
||||
}
|
||||
http.ServeFile(w, r, indexPath)
|
||||
return true
|
||||
}
|
||||
// tenta servir arquivo
|
||||
full := filepath.Join(webDir, filepath.Clean(strings.TrimPrefix(p, "/")))
|
||||
if st, err := os.Stat(full); err == nil && !st.IsDir() {
|
||||
|
||||
if rel == "." {
|
||||
serveIndex(filepath.Join(webDir, "index.html"))
|
||||
return
|
||||
}
|
||||
if !filepath.IsLocal(rel) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
full := filepath.Join(webDir, rel)
|
||||
st, err := os.Stat(full)
|
||||
if err == nil && st.IsDir() {
|
||||
if !strings.HasSuffix(r.URL.Path, "/") {
|
||||
http.Redirect(w, r, r.URL.Path+"/", http.StatusMovedPermanently)
|
||||
return
|
||||
}
|
||||
if serveIndex(filepath.Join(full, "index.html")) {
|
||||
return
|
||||
}
|
||||
} else if err == nil {
|
||||
http.StripPrefix(base, fileServer).ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
http.ServeFile(w, r, filepath.Join(webDir, "index.html"))
|
||||
|
||||
// Em rotas sem extensão, usa o index.html da pasta mais próxima.
|
||||
// Isso permite recarregar rotas internas de SPAs estáticas em web/<site>/.
|
||||
if filepath.Ext(rel) == "" {
|
||||
dir := filepath.Dir(rel)
|
||||
for {
|
||||
if serveIndex(filepath.Join(webDir, dir, "index.html")) {
|
||||
return
|
||||
}
|
||||
parent := filepath.Dir(dir)
|
||||
if parent == dir || dir == "." {
|
||||
break
|
||||
}
|
||||
dir = parent
|
||||
}
|
||||
}
|
||||
http.NotFound(w, r)
|
||||
})
|
||||
|
||||
log.Printf("Servidor rodando em :%s base=%s", cfg.Port, base)
|
||||
|
||||
Reference in New Issue
Block a user