【问题标题】:Chi GoLang http.FileServer returning 404 page not found找不到 Chi GoLang http.FileServer 返回 404 页面
【发布时间】:2020-12-26 00:52:50
【问题描述】:

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

    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/Files/Projects/后端/静态

最小复制库: https://github.com/dragonDScript/repro

【问题讨论】:

  • 您可以在问题中添加请求吗?
  • 当您说“也尝试使用 os.Getwd()”时,您的意思是什么(os.Getwd 返回当前工作目录;将输出添加到您的问题将是有益的)。正如所写,../static 将与当前工作目录相关(可能是也可能不是您的 cmd 文件夹;这取决于您运行应用程序的方式)。
  • 塞拉夫,你是什么意思?
  • 感谢您的更新 - 我假设您在 /mnt/Files/Projects/backend/static 中有相关文件。 Seraf 将寻找您请求的 URL;值得注意的是完整的请求(即http://127.0.0.1/test.html)和您希望返回的文件的完整路径(在检查文件是否存在之后)。我们正在寻找足够的细节来复制您的问题(Minimal, Reproducible Example 会很棒)。
  • 好的,我将完成信息并进行回购。感谢您的关注。

标签: http go go-chi


【解决方案1】:

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

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

所以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")))

【讨论】: