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

如何在 Go 靜態檔案伺服器中將 404 錯誤重新導向至 Index.html?

DDD
發布: 2024-10-28 05:29:30
原創
592 人瀏覽過

How to Redirect 404 Errors to Index.html in a Go Static File Server?

使用靜態檔案伺服器時如何處理遺失檔案錯誤?

使用 FileServer 方法從本機目錄提供靜態檔案時,所有資源根路由已正確提供。例如,對於 myserverurl/index.html 和 myserverurl/styles.css 的請求,提供 index.html 和 style.css 不會出現任何問題。但是,如果向沒有相應文件的路由發出請求,則會傳回 404 錯誤。

要為所有此類路由提供 index.html 並呈現適當的螢幕,可以使用自訂處理程序建立用於包裝 FileServer 處理程序。

建立包裝器

包裝器處理程序建立一個包裝器 http.ResponseWriter,並將其傳遞給 FileServer 處理程序。此包裝器響應編寫器檢查狀態代碼。如果發現狀態碼為404,則不會向客戶端發送回應。相反,它會發送重定向到 /index.html。

以下是包裝器http.ResponseWriter 的範例:

type NotFoundRedirectRespWr struct {
    http.ResponseWriter // We embed http.ResponseWriter
    status              int
}

func (w *NotFoundRedirectRespWr) WriteHeader(status int) {
    w.status = status // Store the status for our own use
    if status != http.StatusNotFound {
        w.ResponseWriter.WriteHeader(status)
    }
}

func (w *NotFoundRedirectRespWr) Write(p []byte) (int, error) {
    if w.status != http.StatusNotFound {
        return w.ResponseWriter.Write(p)
    }
    return len(p), nil // Lie that we successfully written it
}
登入後複製

使用此包裝器來包裝FileServer 處理程序:

func wrapHandler(h http.Handler) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        nfrw := &NotFoundRedirectRespWr{ResponseWriter: w}
        h.ServeHTTP(nfrw, r)
        if nfrw.status == 404 {
            log.Printf("Redirecting %s to index.html.", r.RequestURI)
            http.Redirect(w, r, "/index.html", http.StatusFound)
        }
    }
}
登入後複製

然後註冊包裝的處理程序:

func main() {
    fs := wrapHandler(http.FileServer(http.Dir(".")))
    http.HandleFunc("/", fs)
    panic(http.ListenAndServe(":8080", nil))
}
登入後複製

然後註冊包裝的處理程序來處理請求:

嘗試查詢不存在的文件,如/a.txt3 或favicon.ico,將導致404 錯誤並且請求被重定向到/index.html。

以上是如何在 Go 靜態檔案伺服器中將 404 錯誤重新導向至 Index.html?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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