1 回答

TA貢獻1900條經驗 獲得超5個贊
根據評論,您遇到的主要問題是您正在從文件系統(而不是嵌入式文件系統)提供服務,并且該文件不存在于其中。index.html
第二個問題是嵌入式文件系統將包含單個目錄,因此您需要使用類似的東西才能工作(否則您將需要 - 這適用于您的以及提供索引時.html)。statics, err := fs.Sub(static, "static")s.Open("index.html")static.Open("static/index.html")http.FileServer
注意:您可能不需要以下內容,因為您可以只為路徑運行(因此它提供服務以及子目錄中的文件)。 如果 url 中未提供文件名,則會自動提供服務。http.FileServer/index.htmlhttp.FileServerindex.html
要從嵌入式文件系統中提供服務,您可以將函數重寫為(未經測試!index.html
// default/root handler which serves the index page and associated styling
func indexHandler(w http.ResponseWriter, r *http.Request) {
f, err := s.Open("index.html") // Using `s` from above and assumes its global; better to use handlerfunc and pass filesystem in
if err != nil {
// Send whatever error you want (as file is embedded open should never fail)
return
}
defer f.Close()
w.Header().Set("Content-Type", "text/html")
if _, err := io.Copy(w, f); err != nil { // Write out the file
// Handle error
}
}
上面依賴于一個全局變量(我不熱衷于它),所以我會把它轉換成這樣的東西:
func IndexHandlerFunc(fs fs.FS, h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
f, err := fs.Open("index.html")
if err != nil {
// Send whatever error you want (as file is embedded open should never fail)
return
}
defer f.Close()
w.Header().Set("Content-Type", "text/html")
if _, err := io.Copy(w, f); err != nil { // Write out the file
// Handle error
}
})
}
- 1 回答
- 0 關注
- 141 瀏覽
添加回答
舉報