登录
首页 >  Golang >  Go问答

GoLang http.FileServer返回的页面未找到错误404

来源:stackoverflow

时间:2024-02-20 12:12:24 105浏览 收藏

积累知识,胜过积蓄金银!毕竟在Golang开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《GoLang http.FileServer返回的页面未找到错误404》,就带大家讲解一下知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

我有这个非常简单的代码来提供一些文件:

    wd, _ := os.getwd()
    fs := http.fileserver(http.dir(filepath.join(wd,"../", "static")))

    r.handle("/static", fs)

但这会引发 404 错误。

这个目录是相对于我的 cmd/main.go 的,我也尝试过它相对于当前的包,我也尝试过 os.getwd(),但它不起作用。请注意,我将“不起作用”指的是“不给出任何错误并返回 404 代码”。

我预计,当访问 http://localhost:port/static/afile.png 时,服务器将返回此文件,并具有预期的 mime 类型。

这是我的项目结构:

- cmd
  main.go (main entry)
- static
  afile.png
- internal
  - routes
    static.go (this is where this code is being executed)
go.mod
go.sum

请注意,我还尝试使用 filepath.join()

我也尝试了其他替代方案,但他们也给出了 404 错误。

编辑:这是 static.go 的 os.getwd() 输出:

/mnt/files/projects/backend/cmd(如预期)

这是 fmt.println(filepath.join(wd, "../", "static")) 结果 /mnt/文件/项目/后端/静态

最小复制存储库: https://github.com/dragondscript/repro


解决方案


您的第一个问题是:r.handle("/static", fs)Handle 被定义为 func (mx *mux) handle(pattern string, handler http.handler) 其中 the docspattern 描述为:

每个路由方法都接受 url 模式和处理程序链。 url 模式支持命名参数(即 /users/{userid})和通配符(即 /admin/)。可以在运行时通过调用 chi.urlparam(r, "userid")(对于命名参数)和 chi.urlparam(r, "")(对于通配符参数)来获取 url 参数。

因此 r.handle("/static", fs) 将匹配“/static”且仅匹配“/static”。要匹配低于此的路径,您需要使用 r.handle("/static/*", fs)

第二个问题是您正在请求 http://localhost:port/static/afile.png ,这是从 /mnt/files/projects/backend/static 提供的,这意味着系统正在尝试加载的文件是 /mnt/files/projects/backend/static/static/afile.png。解决此问题的一个简单(但不理想)的方法是从项目根提供服务 (fs := http.fileserver(http.dir(filepath.join(wd, "../"))))。更好的选择是使用 stripprefix;带有硬编码前缀:

fs := http.fileserver(http.dir(filepath.join(wd, "../", "static")))
r.handle("/static/*", http.stripprefix("/static/",fs))

或者 Chi sample code 的方法(请注意,当请求路径而不指定特定文件时,演示还添加了重定向):

fs := http.fileserver(http.dir(filepath.join(wd, "../", "static")))
    r.get("/static/*", func(w http.responsewriter, r *http.request) {
        rctx := chi.routecontext(r.context())
        pathprefix := strings.trimsuffix(rctx.routepattern(), "/*")
        fs := http.stripprefix(pathprefix, fs)
        fs.servehttp(w, r)
    })

注意:使用 os.getwd() 在这里没有任何好处;无论如何,您的应用程序都将访问与此路径相关的文件,因此 filepath.join("../", "static")) 就可以了。如果您想让它相对于可执行文件存储的路径(而不是工作目录),那么您需要类似:

ex, err := os.Executable()
if err != nil {
    panic(err)
}
exPath := filepath.Dir(ex)
fs := http.FileServer(http.Dir(filepath.Join(exPath, "../static")))

今天关于《GoLang http.FileServer返回的页面未找到错误404》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>