[英]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.