0

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

    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/backend/static

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

4

1 回答 1

1

您的第一个问题是:r.Handle("/static", fs). 句柄func (mx *Mux) Handle(pattern string, handler http.Handler)被定义为文档描述pattern为:

每个路由方法都接受一个 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 示例代码的方法(请注意,该演示还为请求路径而不指定特定文件时添加了重定向):

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")))
于 2020-12-27T19:53:53.890 回答