Skip to content

Instantly share code, notes, and snippets.

@syahrul12345
Created October 7, 2019 06:33
Show Gist options
  • Save syahrul12345/91832e7f32024ae816931655b9049f2c to your computer and use it in GitHub Desktop.
Save syahrul12345/91832e7f32024ae816931655b9049f2c to your computer and use it in GitHub Desktop.
Golang mux server multple page app support
router.PathPrefix("/").Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
const staticPath = "../dist"
const indexPath = "index.html"
fileServer := http.FileServer(http.Dir(staticPath))
path, err := filepath.Abs(r.URL.Path)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
path = filepath.Join(staticPath, path)
_, err = os.Stat(path)
if os.IsNotExist(err) {
// file does not exist, serve index.html
http.ServeFile(w, r, filepath.Join(staticPath, indexPath))
return
} else if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fileServer.ServeHTTP(w, r)
}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment