搜尋
首頁後端開發Golang如何處理單頁應用程式的 Go 靜態檔案伺服器中的檔案未找到異常?

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中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
在GO應用程序中有效記錄錯誤在GO應用程序中有效記錄錯誤Apr 30, 2025 am 12:23 AM

有效的Go應用錯誤日誌記錄需要平衡細節和性能。 1)使用標準log包簡單但缺乏上下文。 2)logrus提供結構化日誌和自定義字段。 3)zap結合性能和結構化日誌,但需要更多設置。完整的錯誤日誌系統應包括錯誤enrichment、日誌級別、集中式日誌、性能考慮和錯誤處理模式。

go中的空接口(接口{}):用例和注意事項go中的空接口(接口{}):用例和注意事項Apr 30, 2025 am 12:23 AM

EmptyinterfacesinGoareinterfaceswithnomethods,representinganyvalue,andshouldbeusedwhenhandlingunknowndatatypes.1)Theyofferflexibilityforgenericdataprocessing,asseeninthefmtpackage.2)Usethemcautiouslyduetopotentiallossoftypesafetyandperformanceissues,

比較並發模型:GO與其他語言比較並發模型:GO與其他語言Apr 30, 2025 am 12:20 AM

go'sconcurrencyModelisuniquedUetoItsuseofGoroutinesAndChannels,offeringAlightWeightandefficePappRockhiffcomparredTothread-likeLanguagesLikeLikeJjava,Python,andrust.1)

GO的並發模型:解釋的Goroutines和頻道GO的並發模型:解釋的Goroutines和頻道Apr 30, 2025 am 12:04 AM

go'sconcurrencyModeluessgoroutinesandChannelStomanageConconCurrentPrommmengement.1)GoroutinesArightweightThreadThreadSthAtalLeadSthAtalAlaLeasyParalleAftasks,增強Performance.2)ChannelsfacilitatesfacilitatesafeDataTaAexafeDataTaAexchangeBetnegnegoroutinesGoroutinesGoroutinesGoroutinesGoroutines,crucialforsforsynchrroniz

GO中的接口和多態性:實現代碼可重複使用性GO中的接口和多態性:實現代碼可重複使用性Apr 29, 2025 am 12:31 AM

Interfacesand -polymormormormormormingingoenhancecodereusanity和Maintainability.1)defineInterfaceSattherightabStractractionLevel.2)useInterInterFacesFordEffordExpentIndention.3)ProfileCodeTomeAgePerformancemacts。

'初始化”功能在GO中的作用是什麼?'初始化”功能在GO中的作用是什麼?Apr 29, 2025 am 12:28 AM

initiTfunctioningOrunSautomation beforeTheMainFunctionToInitializePackages andSetUptheNvironment.it'susefulforsettingupglobalvariables,資源和performingOne-timesEtepaskSarpaskSacraskSacrastAscacrAssanyPackage.here'shere'shere'shere'shere'shodshowitworks:1)Itcanbebeusedinanananainapthecate,NotjustAckAckAptocakeo

GO中的界面組成:構建複雜的抽象GO中的界面組成:構建複雜的抽象Apr 29, 2025 am 12:24 AM

接口組合在Go編程中通過將功能分解為小型、專注的接口來構建複雜抽象。 1)定義Reader、Writer和Closer接口。 2)通過組合這些接口創建如File和NetworkStream的複雜類型。 3)使用ProcessData函數展示如何處理這些組合接口。這種方法增強了代碼的靈活性、可測試性和可重用性,但需注意避免過度碎片化和組合複雜性。

在GO中使用Init功能時的潛在陷阱和考慮因素在GO中使用Init功能時的潛在陷阱和考慮因素Apr 29, 2025 am 12:02 AM

initfunctionsingoareAutomationalCalledBeLedBeForeTheMainFunctionandAreuseFulforSetupButcomeWithChallenges.1)executiondorder:totiernitFunctionSrunIndIndefinitionorder,cancancapationSifsUsiseSiftheyDepplothother.2)測試:sterfunctionsmunctionsmunctionsMayInterfionsMayInterferfereWithTests,b

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具