go-chi fileserver示例后端带有vuejs frontend带来错误404当我从浏览器键入路由时找不到错误404

发布于 2025-01-27 16:04:04 字数 574 浏览 2 评论 0原文

文件服务器示例代码:

    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)
    })

运行服务器时,它可以工作 当我单击水疗中心的路由器链接时,它可以正常工作 当我从浏览器中键入链​​接并且不使用水疗中心时,它不起作用并返回404

如何绕过它并为文件提供服务?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

吃不饱 2025-02-03 16:04:04
    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)
    })
    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)
    })
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文