http.Handle("/", http.FileServer(http.Dir("static")))
服务于静态目录中的html
文件.
我们有没有办法指定要提供的html
个文件?
Flask
中大约有render_template
个
我想做一些类似的事情:
http.Handle("/hello", http.FileServer(http.Dir("static/hello.html")))
http.Handle("/", http.FileServer(http.Dir("static")))
服务于静态目录中的html
文件.
我们有没有办法指定要提供的html
个文件?
Flask
中大约有render_template
个
我想做一些类似的事情:
http.Handle("/hello", http.FileServer(http.Dir("static/hello.html")))
也许使用custom http.HandlerFunc
会更简单:
除了你的情况,你的func是http.ServeFile
个,因为只提供一个文件.
例如,参见"Go Web Applications: Serving Static Files":
在您的家庭处理器下方添加以下内容(见下文):
http.HandleFunc("/static/", func(w http.ResponseWriter, r *http.Request) {
// do NOT do this. (see below)
http.ServeFile(w, r, r.URL.Path[1:])
})
This is using the
net/http
package’s ServeFile function to serve our content.
Effectively anything that makes a request starting with the/static/
path will be handled by this function.
One thing I found I had to do in order for the request to be handled correctly was trim the leading ‘/’ using:
r.URL.Path[1:]
Actually, do not do that.
This won't be possible in Go 1.6, as sztanpet comments, with commit 9b67a5d:
If the provided file or directory name is a relative path, it is interpreted relative to the current directory and may ascend to parent directories.
If the provided name is constructed from user input, it should be sanitized before callingServeFile
.
As a precaution,ServeFile
will reject requests wherer.URL.Path
contains a "..
" path element.
这将保护您免受以下"url"的攻击:
/../file
/..
/../
/../foo
/..\\foo
/file/a
/file/a..
/file/a/..
/file/a\\..