'Go-Chi Fileserver Example Backend with VueJS Frontend Brings Error 404 Not Found When I Type A Route From Browser
The Fileserver Example Code:
r.Get(path, func(w http.ResponseWriter, r *http.Request) {
rctx := chi.RouteContext(r.Context()) // sets the route context
pathPrefix := strings.TrimSuffix(rctx.RoutePattern(), "/*") // this displays the path
fmt.Printf(pathPrefix + "\n")
fs := http.StripPrefix(pathPrefix, http.FileServer(root))
fs.ServeHTTP(w, r)
})
When I run the server, it works When I click on router-links from the SPA, it works When I type a link in from the browser and not use the SPA, it doesnt work and returns 404
How do I bypass this and serve the files instead?
Solution 1:[1]
r.Get("/*", func(w http.ResponseWriter, r *http.Request) {
workDir, _ := os.Getwd()
filesDir := filepath.Join(workDir, "dist")
if _, err := os.Stat(filesDir + r.URL.Path); errors.Is(err, os.ErrNotExist) {
http.ServeFile(w, r, filepath.Join(filesDir, "index.html"))
}
http.ServeFile(w, r, filesDir+r.URL.Path)
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | darylvickerman |
