Created
October 7, 2019 06:33
-
-
Save syahrul12345/91832e7f32024ae816931655b9049f2c to your computer and use it in GitHub Desktop.
Golang mux server multple page app support
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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