初學者圍棋問題我有這個目錄結構。app_executablehtml | - index.htmldata | - static_file.json我無法讓它為static_file.jsonin服務data/static_file.json。func main() { // this works and serves html/index.html html := http.FileServer(http.Dir("html")) http.Handle("/", html) // this always 404's data := http.FileServer(http.Dir("data")) http.Handle("/data/", data) fmt.Println("Listening on port " + port + "...") log.Fatal(http.ListenAndServe(port, nil))}任何幫助表示贊賞!
1 回答

Smart貓小萌
TA貢獻1911條經驗 獲得超7個贊
問題在于 FileServer 處理程序實際上正在此路徑上查找文件:
./data/data/static_file.json
代替
./data/statif_file.json
如果您使第一個文件存在,您的代碼將起作用。您可能想要做的是:
data := http.FileServer(http.Dir("data"))
http.Handle("/", data)
或者
data := http.FileServer(http.Dir("data"))
http.Handle("/data/", http.StripPrefix("/data/", data))
我會選擇前者,因為這可能是您真正想要做的。將處理程序附加到根目錄,任何匹配 /data/ 的內容都將按預期返回。
如果您查看從調用中實際返回的內容
data := http.FileServer(http.Dir("data"))
你會看到它是
&http.fileHandler{root:"data"}
這就是說根位于 ./data,因此請嘗試在該根下查找與請求路徑匹配的文件。在你的情況下,路徑是 data/static_file.json 所以最終它會檢查不存在的 ./data/data/static_file.json 并且它是 404s
- 1 回答
- 0 關注
- 267 瀏覽
添加回答
舉報
0/150
提交
取消