首頁 > 後端開發 > Golang > 主體

如何處理單頁應用程式的 Go 靜態檔案伺服器中的檔案未找到異常?

Patricia Arquette
發布: 2024-10-28 02:32:02
原創
789 人瀏覽過

How to Handle File Not Found Exceptions in a Go Static File Server for Single-Page Applications?

在Go 靜態檔案伺服器中處理檔案未找到異常

在Go 應用程式中,您正在利用單頁Web 應用程式並使用靜態檔案伺服器提供其資源檔案伺服器。雖然伺服器可以很好地為根目錄中的現有資源提供服務,但如果請求的檔案不存在,它會拋出 404 Not Found 錯誤。

您的目標是修改伺服器的行為,以便為任何內容提供 index.html無法辨識的網址。這一點至關重要,因為您的單頁應用程式根據所提供的 HTML 和 JavaScript 處理渲染。

自訂未找到檔案處理

http.FileServer() 提供的預設處理程序缺少自訂選項,包括處理 404 未找到回應。為了解決這個限制,我們將包裝處理程序並在包裝器中實現我們的邏輯。

製作自訂 HTTP 回應編寫器

我們將建立一個包裝原始內容的自訂 http.ResponseWriter回覆作家。此自訂回應編寫器將:

  1. 檢查回應狀態,特別是尋找 404 狀態碼。
  2. 如果偵測到 404 狀態碼,而不是向客戶端發送回應,我們將發送 302 Found 重定向回應到 /index.html。

以下是此類自訂回應編寫器的範例:

<code class="go">type NotFoundRedirectRespWr struct {
    http.ResponseWriter // Embed the base HTTP response writer
    status              int
}

func (w *NotFoundRedirectRespWr) WriteHeader(status int) {
    w.status = status // Store the status code
    if status != http.StatusNotFound {
        w.ResponseWriter.WriteHeader(status) // Proceed normally for non-404 statuses
    }
}

func (w *NotFoundRedirectRespWr) Write(p []byte) (int, error) {
    if w.status != http.StatusNotFound {
        return w.ResponseWriter.Write(p) // Proceed normally for non-404 statuses
    }
    return len(p), nil // Pretend that the data was successfully written, but discard it
}</code>
登入後複製

包裝預設處理程序

接下來,我們包裝http.FileServer()傳回的處理程序。包裝器處理程序將:

  1. 呼叫預設處理程序。
  2. 如果預設處理程序在我們的自訂回應編寫器中設定 404 狀態程式碼,則此包裝器將攔截回應。
  3. 它不會發送 404 回應,而是將請求重定向到 /index.html,狀態為 302 Found。

以下是包裝處理程序的範例:

<code class="go">func wrapHandler(h http.Handler) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        nfrw := &NotFoundRedirectRespWr{ResponseWriter: w}
        h.ServeHTTP(nfrw, r) // Call the default handler with our custom response writer
        if nfrw.status == 404 {
            log.Printf("Redirecting %s to index.html.", r.RequestURI)
            http.Redirect(w, r, "/index.html", http.StatusFound)
        }
    }
}</code>
登入後複製

將它們放在一起

現在,在main() 函數中,利用包裝處理程序來修改靜態檔案伺服器的行為。

<code class="go">func main() {
    fs := wrapHandler(http.FileServer(http.Dir("."))) // Wrap the handler
    http.HandleFunc("/", fs)
    panic(http.ListenAndServe(":8080", nil)) // Start serving files with the custom handler
}</code>
登入後複製

透過這種方法,所有對與不存在的文件相對應的 URL 的請求將觸發到 index.html 的重定向。您的單頁應用程式將按預期運行,根據所提供的 HTML 和 JavaScript 呈現適當的內容。

以上是如何處理單頁應用程式的 Go 靜態檔案伺服器中的檔案未找到異常?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!