Go-Chi Fileserver Example Backend with VueJS Frontend Brings Error 404 Not Found When I Type A Route From Browser

811 views Asked by At

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?

1

There are 1 answers

0
darylvickerman On
    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)
    })