Serving SPA with Golang and Chi router enters a loop
I´m trying to serve a SPA with Golang and solving the 404 error became a challenge.
- In the init() func I buffered into memory the index.html file.
- I created a indexHandler that returns the index file buffered.
- I call the indexHandler in the router.NotFound() func so the route is returned to the SPA.
- I serve the rest of the static files with FileServer.
The problem is that it seems to be in a loop, when I try to access the app in the browser, it reloads itself indefinitely.
package main
import (
"log"
"net/http"
"os"
"path/filepath"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/joho/godotenv"
)
var indexBuffer []byte
func main() {
r := chi.NewRouter()
r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
fs := http.FileServer(http.Dir(os.Getenv("FRONTEND_PATH")))
r.Handle("/app/static/*", http.StripPrefix("/app/static/", fs))
apiRouter := chi.NewRouter()
apiRouter.Get("/cargas", handlerCargas)
r.Mount("/app/api", apiRouter)
r.NotFound(indexHandler)
log.Fatal(http.ListenAndServe(":8000", r))
}
func init() {
err := godotenv.Load()
if err != nil {
log.Fatal("Erro ao ler .env verifique!")
}
indexBuffer, err = os.ReadFile(filepath.Join(os.Getenv("FRONTEND_PATH"), "index.html"))
if err != nil {
log.Fatal("Erro ao tentar bufferizar a index na init().")
}
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
w.Write(indexBuffer)
}
I´m expecting index.html to be served by the indexHandler and the rest of the files be served by the FileServer and errors of page not found be handled by the SPA.
Comments
Post a Comment