繁体   English   中英

Chi GoLang http.FileServer 返回 404 页面未找到

[英]Chi GoLang http.FileServer returning 404 page not found

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

    wd, _ := os.Getwd()
    fs := http.FileServer(http.Dir(filepath.Join(wd,"../", "static")))

    r.Handle("/static", fs)

但这是抛出 404 错误。

这个目录是相对于我的cmd/main.go,我也试过它是相对于当前的package,我也试过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() output:

/mnt/Files/Projects/backend/cmd(如预期的那样)

这是 fmt.Println(filepath.Join(wd, "../", "static")) 结果 /mnt/Files/Projects/backend/static

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

您的第一个问题是: 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示例代码的做法(注意demo中还添加了在请求路径时不指定具体文件时的重定向):

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM