Serve an SPA from a Go backend by mounting a static file handler for the built frontend assets and adding a fallback handler to return index.html for all other routes.
package main
import (
"net/http"
"path/filepath"
)
func main() {
fs := http.FileServer(http.Dir("./dist"))
mux := http.NewServeMux()
mux.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if filepath.Ext(r.URL.Path) != "" {
fs.ServeHTTP(w, r)
return
}
http.ServeFile(w, r, "./dist/index.html")
}))
http.ListenAndServe(":8080", mux)
}
- Build your React or Vue app to a
distdirectory containingindex.htmland assets. - Run the Go server above to serve static files and fallback to
index.htmlfor client-side routing.