1 回答

TA貢獻1820條經驗 獲得超2個贊
您的第一個問題是:r.Handle("/static", fs). 句柄func (mx *Mux) Handle(pattern string, handler http.Handler)被定義為文檔描述pattern為:
每個路由方法都接受一個 URL 模式和處理程序鏈。URL 模式支持命名參數(即 /users/{userID})和通配符(即 /admin/ )。URL 參數可以在運行時通過調用 chi.URLParam(r, "userID") 獲取命名參數和 chi.URLParam(r, " ") 獲取通配符參數。
所以r.Handle("/static", fs)將匹配“/static”并且只匹配“/static”。要匹配低于此的路徑,您需要使用r.Handle("/static/*", fs).
第二個問題是您正在請求http://localhost:port/static/afile.png,這/mnt/Files/Projects/backend/static意味著系統嘗試加載的文件是/mnt/Files/Projects/backend/static/static/afile.png. 解決此問題的一種簡單(但不理想)的方法是從項目根目錄 ( fs := http.FileServer(http.Dir(filepath.Join(wd, "../")))) 提供服務。更好的選擇是使用StripPrefix; 要么帶有硬編碼前綴:
fs := http.FileServer(http.Dir(filepath.Join(wd, "../", "static")))
r.Handle("/static/*", http.StripPrefix("/static/",fs))
或者Chi 示例代碼的方法(請注意,該演示還為請求路徑而不指定特定文件時添加了重定向):
fs := http.FileServer(http.Dir(filepath.Join(wd, "../", "static")))
r.Get("/static/*", func(w http.ResponseWriter, r *http.Request) {
rctx := chi.RouteContext(r.Context())
pathPrefix := strings.TrimSuffix(rctx.RoutePattern(), "/*")
fs := http.StripPrefix(pathPrefix, fs)
fs.ServeHTTP(w, r)
})
注意:os.Getwd()在這里使用沒有任何好處;在任何情況下,您的應用程序都將訪問與此路徑相關的文件,所以filepath.Join("../", "static"))很好。如果你想讓它相對于存儲可執行文件的路徑(而不是工作目錄),那么你想要這樣的東西:
ex, err := os.Executable()
if err != nil {
panic(err)
}
exPath := filepath.Dir(ex)
fs := http.FileServer(http.Dir(filepath.Join(exPath, "../static")))
- 1 回答
- 0 關注
- 149 瀏覽
添加回答
舉報