3 回答

TA貢獻(xiàn)1906條經(jīng)驗(yàn) 獲得超3個(gè)贊
也許使用自定義http.HandlerFunc會(huì)更容易:
除了您的情況,您的 func 將是http.ServeFile唯一的,用于僅提供一個(gè)文件。
參見例如“ Go Web Applications:Serving Static Files ”:
在您的家庭處理程序下方添加以下內(nèi)容 (見下文):
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 函數(shù)來提供我們的內(nèi)容。
實(shí)際上,任何以/static/路徑開頭的請(qǐng)求都將由該函數(shù)處理。
我發(fā)現(xiàn)為了正確處理請(qǐng)求我必須做的一件事是使用以下方法修剪前導(dǎo)“/”:
r.URL.Path[1:]
實(shí)際上,不要這樣做。
這在 Go 1.6 中是不可能的,正如sztanpet 評(píng)論的那樣,提交 9b67a5d:
如果提供的文件或目錄名稱是相對(duì)路徑,則它相對(duì)于當(dāng)前目錄進(jìn)行解釋,并可能上升到父目錄。
如果提供的名稱是根據(jù)用戶輸入構(gòu)造的,則應(yīng)在調(diào)用ServeFile.
作為預(yù)防措施,ServeFile將拒絕r.URL.Path包含“ ..”路徑元素的請(qǐng)求。
這將防止以下“網(wǎng)址”:
/../file
/..
/../
/../foo
/..\\foo
/file/a
/file/a..
/file/a/..
/file/a\\..

TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超4個(gè)贊
你可以用 http.StripPrefix
像這樣:
http.Handle("/hello/", http.StripPrefix("/hello/",http.FileServer(http.Dir("static"))))

TA貢獻(xiàn)1155條經(jīng)驗(yàn) 獲得超0個(gè)贊
也許我在這里遺漏了一些東西,但經(jīng)過大量混亂的搜索,我把它放在一起:
...
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 作為簡單上傳和下載服務(wù)器的一部分被調(diào)用:
func main() {
http.HandleFunc("/upload", uploadHandler)
http.HandleFunc("/download", downloadHandler)
http.ListenAndServe(":3001", nil)
}
適用于 Firefox 和 Chrome。甚至不需要文件類型。
- 3 回答
- 0 關(guān)注
- 262 瀏覽
添加回答
舉報(bào)