【问题标题】:Golang net/http fileserver giving 404 on any pattern other than "/"Golang net/http 文件服务器在“/”以外的任何模式上给出 404
【发布时间】:2018-01-14 09:57:20
【问题描述】:

你好,很棒的 stackoverflow 社区,

为这个蹩脚的问题道歉。 我一直在玩 Go 中的 net/http 包,并试图设置一个 http.Handle 来提供目录的内容。我的句柄代码是

 func main() {
     http.Handle("/pwd", http.FileServer(http.Dir(".")))
     http.HandleFunc("/dog", dogpic)
     err := http.ListenAndServe(":8080", nil)
     if err != nil {
         panic(err)
     }
 } 

我的 dogpic 处理程序正在使用 os.Openhttp.ServeContent,工作正常。

但是,当我尝试浏览 localhost:8080/pwd 时,我得到了一个 404 页面,但是当我将模式更改为路由到 / 时,

http.Handle("/", http.FileServer(http.Dir(".")))

它正在显示当前页面的内容。有人可以帮我弄清楚为什么fileserver 不能与其他模式一起使用,而只能与/ 一起使用吗?

谢谢。

【问题讨论】:

    标签: http go http-status-code-404 handler


    【解决方案1】:

    使用/pwd 处理程序调用的http.FileServer 将接受/pwdmyfile 的请求,并将使用URI 路径来构建文件名。这意味着它将在本地目录中查找pwdmyfile

    我怀疑您只希望 pwd 作为 URI 的前缀,而不是文件名本身。

    http.FileServer 文档中有一个如何执行此操作的示例:

    // To serve a directory on disk (/tmp) under an alternate URL
    // path (/tmpfiles/), use StripPrefix to modify the request
    // URL's path before the FileServer sees it:
    http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
    

    你会想做类似的事情:

    http.Handle("/pwd", http.StripPrefix("/pwd", http.FileServer(http.Dir("."))))
    

    【讨论】:

    • 默认情况下,内置多路复用器将使用完全匹配。如果路径以斜杠结尾,则它只是一个前缀(目录)匹配。所以http.Handle("/pwd"... 将匹配仅精确路径 /pwd,而http.Handle("/pwd/"... 将匹配以/pwd/per the documentation 开头的任何内容。
    【解决方案2】:

    你应该写http.Handle("/pwd", http.FileServer(http.Dir("./")))

    http.Dir 引用系统目录。

    如果你想要 localhost/ 然后使用 http.Handle("/pwd", http.StripPrefix("/pwd", http.FileServer(http.Dir("./pwd"))))

    它将为您在 localhost/ 的 /pwd 目录中提供所有服务

    【讨论】:

      猜你喜欢
      • 2017-04-02
      • 1970-01-01
      • 2014-08-19
      • 1970-01-01
      • 1970-01-01
      • 2018-09-16
      • 1970-01-01
      • 1970-01-01
      • 2021-02-22
      相关资源
      最近更新 更多