为什么我需要使用http.StripPrefix来访问我的静态文件?
main.go
package main import ( "net/http" ) func main() { http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static")))) http.ListenAndServe(":8080", nil) }
目录结构:
%GOPATH%/src/project_name/main.go %GOPATH%/src/project_name/static/..files and folders ..
即使在阅读文档之后,我仍然无法理解http.StripPrefix在这里的作用。
1)为什么我不能访问localhost:8080/static如果我删除http.StripPrefix ?
2)如果我删除该function,什么URL映射到/static文件夹?
http.StripPrefix()将请求处理转发给您指定的参数,但在此之前,通过剥离指定的前缀来修改请求URL。
所以例如在你的情况下,如果浏览器(或HTTP客户端)请求资源:
/static/example.txt
StripPrefix将剪切/static/并将修改后的请求转发给http.FileServer()返回的处理程序,以便看到请求的资源是
/example.txt
http.FileServer()返回的Handler会查找并提供指定为其参数(指定"static"为静态文件根目录)的文件夹(或FileSystem )的文件内容。
现在,由于"example.txt"位于static文件夹中,因此必须指定相对path来获取corrent文件path。
另一个例子
这个例子可以在http包的文档页面( 这里 )find:
// 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"))))
说明:
FileServer()被告知静态文件的根目录是"/tmp" 。 我们希望url以"/tmpfiles/" 。 所以如果有人请求"/tempfiles/example.txt" ,我们希望服务器发送文件"/tmp/example.txt" 。
为了达到这个目的,我们必须从URL中"/tmpfiles" ,剩下的就是相对于根文件夹"/tmp"的相对path,如果我们join的话:
/tmp/example.txt
我会一一回答这两个问题。
问题1的答案1:如果您的代码如下所示:
http.Handle("/static/", http.FileServer(http.Dir("static"))
您的根文件夹是%GOPATH%/src/project_name/static/ 。 当你访问localhost:8080/static ,URL /static将被转发给http.FileServer()返回的处理程序。 但是,根文件夹中没有名为static目录或文件。
问题2的回答2 :通常,如果删除http.StripPrefix() ,则无法访问/static文件夹。 但是,如果您有一个名为static的目录或文件,则可以使用URL localhost:8080:/static来访问它( 完全不是您想要的根目录 )。
顺便说一下,如果你的URL不是以/static开头的,你不能访问任何东西,因为http.ServeMux不会redirect你的请求。