php小編香蕉發現,在使用Go語言開發Web端應用時,有時會遇到一個常見的問題:當我們嘗試訪問Web端點時,卻收到一個404錯誤,提示找不到靜態index.html文件。這個問題可能會讓開發者感到困惑,特別是對于初學者來說。那么,我們應該如何解決這個問題呢?接下來,我們將詳細介紹解決方案,幫助你順利解決這個問題。
問題內容
這是我的代碼:
package main import ( "fmt" "log" "net/http" ) const customport = "3001" func main() { fileserver := http.fileserver(http.dir("./static")) port:= fmt.sprintf(":%s", customport) http.handle("/", fileserver) fmt.printf("starting front end service on port %s", port) err := http.listenandserve(port, nil) if err != nil { log.panic(err) } }
登錄后復制
頂級文件夾是 microservices
并設置為 go 工作區。該網絡服務將是眾多服務之一。它位于以下文件夾中:
microservices |--frontend |--cmd |--web |--static |--index.html |--main.go
登錄后復制
我位于頂級微服務文件夾中,我以以下方式啟動它:go run ./frontend/cmd/web
。它啟動正常,沒有錯誤。但是當我轉到 chrome 并輸入 http://localhost:3001
時,我得到 404 頁面未找到。即使 http://localhost:3001/index.html
也會給出 404 頁面未找到。我剛剛學習 go,不知道為什么找不到 ./static
文件夾?
解決方法
根據您的命令,路徑必須是./frontend/cmd/web/static,而不僅僅是./static。那不是便攜式的;路徑隨工作目錄而變化。
考慮嵌入靜態目錄。否則,您必須使路徑可配置(標志、環境變量等)
嵌入的缺點是您必須在對靜態文件進行任何更改后重建程序。
您還可以使用混合方法。如果設置了標志(或其他),則使用它從磁盤提供服務,否則使用嵌入式文件系統。該標志在開發過程中很方便,并且嵌入式文件系統使部署變得容易,因為您只需復制程序二進制文件。
package main import ( "embed" "flag" "io/fs" "net/http" "os" ) //go:embed web/static var embeddedAssets embed.FS func main() { var staticDir string flag.StringVar(&staticDir, "static-dir", staticDir, "Path to directory containing static assets. If empty embedded assets are used.") flag.Parse() var staticFS fs.FS = embeddedAssets if staticDir != "" { staticFS = os.DirFS(staticDir) } http.Handle("/", http.FileServer(http.FS(staticFS))) // ... }
登錄后復制