3 回答

TA貢獻1906條經驗 獲得超3個贊
也許使用自定義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\\..

TA貢獻1811條經驗 獲得超4個贊
你可以用 http.StripPrefix
像這樣:
http.Handle("/hello/", http.StripPrefix("/hello/",http.FileServer(http.Dir("static"))))

TA貢獻1155條經驗 獲得超0個贊
也許我在這里遺漏了一些東西,但經過大量混亂的搜索,我把它放在一起:
...
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。甚至不需要文件類型。
- 3 回答
- 0 關注
- 270 瀏覽
添加回答
舉報