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

Golang net/http文件服务器以“/”以外的任何模式提供404,http,go,http-status-code-404,handler,Http,Go,Http Status Code 404,Handler,你好,我的社区 为这个蹩脚的问题道歉。 我一直在使用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 {

你好,我的社区

为这个蹩脚的问题道歉。 我一直在使用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页面未找到,但当我将模式更改为route to/时,如图所示

它显示当前页面的内容。有人能帮我弄清楚为什么文件服务器不使用其他模式,而只使用/

谢谢。

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

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

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

您将需要执行类似的操作:

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

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

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

您将需要执行类似的操作:

http.Handle("/pwd", http.StripPrefix("/pwd", http.FileServer(http.Dir("."))))
您应该编写http.Handle/pwd、http.FileServerhttp.Dir/

Dir引用一个系统目录

如果您想要localhost/则使用http.Handle/pwd、http.StripPrefix/pwd、http.FileServerhttp.Dir./pwd

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

您应该编写http.Handle/pwd、http.FileServerhttp.Dir/

Dir引用一个系统目录

如果您想要localhost/则使用http.Handle/pwd、http.StripPrefix/pwd、http.FileServerhttp.Dir./pwd


它将为您在localhost/

的/pwd目录中提供所有服务,并且默认情况下,内置mux将使用精确匹配。如果路径以斜杠结尾,则仅为前缀目录匹配。所以http.Handle/pwd。。。将仅匹配精确路径/pwd,而http.Handle/pwd/。。。将匹配以/pwd/,,开头的任何内容。此外,默认情况下,内置mux将使用精确匹配。如果路径以斜杠结尾,则仅为前缀目录匹配。所以http.Handle/pwd。。。将仅匹配精确路径/pwd,而http.Handle/pwd/。。。将匹配以/pwd/,,开头的任何内容。
http.Handle("/pwd", http.StripPrefix("/pwd", http.FileServer(http.Dir("."))))