Golang net/http 文件服务器在“/”以外的任何模式上给出 404

Golang net/http fileserver giving 404 on any pattern other than "/"

你好很棒的 Whosebug 社区,

抱歉这个蹩脚的问题。 我一直在玩 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.Open 和一个 http.ServeContent,工作正常。

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

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

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

谢谢。

使用 /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", http.FileServer(http.Dir("./")))

http.Dir 引用系统目录。

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

它将为您在本地主机/

的 /pwd 目录中提供所有内容