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) 为什么我删除http.StripPrefix
后无法访问localhost:8080/static
?
2) 如果我删除该函数,哪个 URL 映射到 /static
文件夹?
最佳答案
http.StripPrefix()
将请求的处理转发给您指定为其参数的请求,但在此之前它会通过剥离指定的前缀来修改请求 URL。
例如,如果浏览器(或 HTTP 客户端)请求资源:
/static/example.txt
StripPrefix
会剪切 /static/
并将修改后的请求转发给 http.FileServer()
返回的处理程序所以它会看到请求的资源是
/example.txt
http.FileServer()
返回的 Handler
将查找文件relative 的内容并将其提供给文件夹(或者更确切地说FileSystem
) 指定为其参数(您将 "static"
指定为静态文件的根)。
现在由于 "example.txt"
位于 static
文件夹中,您必须指定相对路径才能获得正确的文件路径。
另一个例子
此示例可在 http 包文档页面 (here ) 上找到:
// 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"
的相对路径,如果我们加入的话:
/tmp/example.txt
关于http - 为什么我需要使用 http.StripPrefix 来访问我的静态文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27945310/