[英]Go Golang to serve a specific html file
http.Handle("/", http.FileServer(http.Dir("static")))
在静态目录中提供html
文件。
在 Go 中有什么方法可以指定要提供的html
文件吗?
类似于Flask
render_template
我想做类似的事情:
http.Handle("/hello", http.FileServer(http.Dir("static/hello.html")))
也许使用自定义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:])
})
这是使用
net/http
包的 ServeFile 函数来提供我们的内容。
实际上,任何以/static/
路径开头的请求都将由该函数处理。
我发现为了正确处理请求我必须做的一件事是使用以下方法修剪前导“/”:
r.URL.Path[1:]
实际上,不要这样做。
这在 Go 1.6 中是不可能的,正如sztanpet 评论的那样, 提交 9b67a5d :
如果提供的文件或目录名称是相对路径,则它相对于当前目录进行解释,并可能上升到父目录。
如果提供的名称是根据用户输入构造的,则应在调用ServeFile
之前对其进行清理。
作为预防措施,ServeFile
将拒绝r.URL.Path
包含“..
”路径元素的请求。
这将防止以下“网址”:
/../file
/..
/../
/../foo
/..\\foo
/file/a
/file/a..
/file/a/..
/file/a\\..
你可以使用http.StripPrefix
像这样:
http.Handle("/hello/", http.StripPrefix("/hello/",http.FileServer(http.Dir("static"))))
也许我在这里遗漏了一些东西,但经过大量混乱的搜索,我把它放在一起:
...
func downloadHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
StoredAs := r.Form.Get("StoredAs") // file name
data, err := ioutil.ReadFile("files/"+StoredAs)
if err != nil { fmt.Fprint(w, err) }
http.ServeContent(w, r, StoredAs, time.Now(), bytes.NewReader(data))
}
...
其中 downloadHandler 作为简单上传和下载服务器的一部分被调用:
func main() {
http.HandleFunc("/upload", uploadHandler)
http.HandleFunc("/download", downloadHandler)
http.ListenAndServe(":3001", nil)
}
适用于 Firefox 和 Chrome。 甚至不需要文件类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.