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

noh*_*hup 1 http handler go http-status-code-404

你好很棒的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)
     }
 } 
Run Code Online (Sandbox Code Playgroud)

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

但是,当我尝试浏览localhost:8080/pwd时,找不到 404 页面,但是当我将模式更改为 route to 时/,如

http.Handle("/", http.FileServer(http.Dir(".")))
Run Code Online (Sandbox Code Playgroud)

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

谢谢你。

Mar*_*arc 5

http.FileServer使用您的/pwd处理程序调用的as将接受请求/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"))))
Run Code Online (Sandbox Code Playgroud)

你会想做类似的事情:

http.Handle("/pwd", http.StripPrefix("/pwd", http.FileServer(http.Dir("."))))
Run Code Online (Sandbox Code Playgroud)

  • 此外,默认情况下,内置多路复用器将使用精确匹配。如果路径以斜杠结尾,则它只是前缀(目录)匹配。所以`http.Handle("/pwd"...` 将匹配*精确的路径* `/pwd`,而`http.Handle("/pwd/"...` 将匹配任何以`/pwd 开头的内容/`,[根据文档](https://golang.org/pkg/net/http/#ServeMux)。 (2认同)