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

huangapple go评论69阅读模式
英文:

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

问题

文件服务器示例代码:

	r.Get(path, func(w http.ResponseWriter, r *http.Request) {
		rctx := chi.RouteContext(r.Context())                       // 设置路由上下文
		pathPrefix := strings.TrimSuffix(rctx.RoutePattern(), "/*") // 显示路径
		fmt.Printf(pathPrefix + "\n")
		fs := http.StripPrefix(pathPrefix, http.FileServer(root))
		fs.ServeHTTP(w, r)
	})

当我运行服务器时,它可以工作。
当我从SPA点击路由链接时,它可以工作。
当我在浏览器中输入链接而不使用SPA时,它无法工作并返回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?

答案1

得分: 2

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

这段代码是一个用于处理 HTTP 请求的 Go 语言代码。它使用了 Gorilla Mux 路由库来处理路由。当请求的 URL 匹配到 "/*" 时,会执行后面的处理函数。

处理函数中,首先获取当前工作目录,并将其与 "dist" 目录拼接成文件目录路径。然后,通过判断请求的 URL 对应的文件是否存在,来确定是否需要返回 "index.html" 文件。如果文件不存在,则返回 "index.html" 文件;如果文件存在,则返回请求的文件。

最后,通过调用 http.ServeFile 函数来将文件内容写入到 HTTP 响应中,从而返回给客户端。

英文:
	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)
	})

huangapple
  • 本文由 发表于 2022年5月11日 00:34:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/72190011.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定