Dan*_*nte 32 http url-rewriting url-routing go server
main.go
package main
import (
"net/http"
)
func main() {
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
http.ListenAndServe(":8080", nil)
}
Run Code Online (Sandbox Code Playgroud)
目录结构:
%GOPATH%/src/project_name/main.go
%GOPATH%/src/project_name/static/..files and folders ..
Run Code Online (Sandbox Code Playgroud)
即使在阅读完文档后,我也无法理解http.StripPrefix
这里究竟是做什么的.
1)localhost:8080/static
如果删除,为什么我无法访问http.StripPrefix
?
2)/static
如果删除该功能,哪个URL映射到文件夹?
icz*_*cza 38
http.StripPrefix()
将请求的处理转发给您指定为其参数的请求,但在此之前,它会通过剥离指定的前缀来修改请求URL.
例如,在您的情况下,如果浏览器(或HTTP客户端)请求资源:
/static/example.txt
Run Code Online (Sandbox Code Playgroud)
StripPrefix
将/static/
修改后的请求剪切并转发给返回的处理程序,http.FileServer()
以便它将看到所请求的资源
/example.txt
Run Code Online (Sandbox Code Playgroud)
在Handler
通过返回http.FileServer()
将寻找和文件的内容服务相关的文件夹(或相当FileSystem
)指定为其参数(指定"static"
为静态文件的根目录).
现在,因为"example.txt"
在static
文件夹中,您必须指定相对路径以获取相关文件路径.
这个例子可以在http包文档页面(这里)找到:
// 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)
说明:
FileServer()
被告知静态文件的根目录是"/tmp"
.我们希望URL开头"/tmpfiles/"
.因此,如果有人请求"/tempfiles/example.txt"
,我们希望服务器发送文件"/tmp/example.txt"
.
为了实现这一点,我们必须"/tmpfiles"
从URL中剥离,剩下的将是与根文件夹相比的相对路径"/tmp"
,如果我们加入则给出:
/tmp/example.txt
Run Code Online (Sandbox Code Playgroud)
小智 5
我有一个档案
/home/go/src/js/kor.js
Run Code Online (Sandbox Code Playgroud)
然后,告诉fileserve服务本地目录
fs := http.FileServer(http.Dir("/home/go/src/js"))
Run Code Online (Sandbox Code Playgroud)
现在文件服务器将"/"
请求作为"/home/go/src/js"+"/"
http.Handle("/", fs)
Run Code Online (Sandbox Code Playgroud)
是的,http://localhost/kor.js
请求告诉Fileserver,kor.js
在
"/home/go/src/js" + "/" + "kor.js".
Run Code Online (Sandbox Code Playgroud)
我们有kor.js
文件。
但是,如果添加其他请求名称。
http.Handle("/static/", fs)
Run Code Online (Sandbox Code Playgroud)
现在文件服务器将"/static/"
请求作为"/home/go/src/js"+"/static/"
是的,http://localhost/static/kor.js
请求告诉Fileserver,kor.js
在
"/home/go/src/js" + "/static/" + "kor.js".
Run Code Online (Sandbox Code Playgroud)
我们收到404错误。
因此,我们在Fileserver接收请求网址之前先修改请求网址 http.StripPrefix("/tmpfiles/", ...
在stripPrefix
Fileserver /
取而代之之后/static/
"/home/go/src/js" + "/" + "kor.js".
Run Code Online (Sandbox Code Playgroud)
得到 kor.js