首頁  >  文章  >  後端開發  >  Go Web端點找不到靜態index.html文件

Go Web端點找不到靜態index.html文件

WBOY
WBOY轉載
2024-02-09 11:18:171014瀏覽

Go Web端点找不到静态index.html文件

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)))

    // ...
}

以上是Go Web端點找不到靜態index.html文件的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除