使用標準HTTP 套件顯示自訂404 錯誤頁面
當使用者要求不存在的URL 時,HTTP 伺服器通常會顯示基本的“404 頁面找不到”錯誤訊息。為了提供更多資訊或客製化的體驗,有必要實作自訂錯誤頁面處理程序。
Go 的標準 HTTP 套件中,存在一種機制來處理所有未處理的請求並顯示自訂錯誤頁面。讓我們深入研究如何實現這一點:
自訂錯誤處理函數
建立一個函數來處理自訂錯誤頁面。此函數採用三個參數:
- w (http.ResponseWriter):用於傳送自訂錯誤頁面的回應編寫器。
- r (*http.Request): 不存在的請求物件URL。
- status (int):錯誤的狀態碼(通常為 http.StatusNotFound)。
func errorHandler(w http.ResponseWriter, r *http.Request, status int) { // Set the HTTP status code. w.WriteHeader(status) // Customize the error response for specific status codes. if status == http.StatusNotFound { fmt.Fprint(w, "Custom 404 error message") } }
設定自訂錯誤Handler
錯誤處理函數需要連結到HTTP伺服器。這是在 http.ListenAndServe 函數中完成的,該函數在指定連接埠上啟動伺服器。
http.ListenAndServe(":12345", nil)
將 nil 替換為處理所有請求的自訂 HTTP 請求處理程序。
http.ListenAndServe(":12345", new(http.ServeMux))
在 ServeMux 中,新增特定 URL 的原始路由處理程序。
mux := http.NewServeMux() mux.HandleFunc("/smth/", smthHandler) mux.HandleFunc("/", homeHandler) http.ListenAndServe(":12345", mux)
最後,加入NotFoundHandler 到 ServeMux 來處理特定路由處理程序未處理的所有其他 URL。
mux.NotFoundHandler = http.HandlerFunc(errorHandler)
範例程式碼
實作上述方法的完整範例程式碼是如下所示:
package main import ( "fmt" "net/http" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/smth/", smthHandler) mux.HandleFunc("/", homeHandler) mux.NotFoundHandler = http.HandlerFunc(errorHandler) http.ListenAndServe(":12345", mux) } func smthHandler(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/smth/" { errorHandler(w, r, http.StatusNotFound) return } fmt.Fprint(w, "Welcome to smth") } func homeHandler(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { errorHandler(w, r, http.StatusNotFound) return } fmt.Fprint(w, "Welcome home") } func errorHandler(w http.ResponseWriter, r *http.Request, status int) { w.WriteHeader(status) if status == http.StatusNotFound { fmt.Fprint(w, "Custom 404 error message") } }
此程式碼定義特定URL 的路由處理程序(/smth/和/) 並指派自訂錯誤處理函數(errorHandler) 來處理所有其他未處理的請求。當使用者嘗試存取不存在的 URL 時,將顯示自訂 404 錯誤頁面,而不是預設的「404 頁面未找到」訊息。
以上是如何在Go的標準HTTP包中實作自訂404錯誤頁面?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Go語言使用"encoding/binary"包進行二進制編碼與解碼。 1)該包提供binary.Write和binary.Read函數,用於數據的寫入和讀取。 2)需要注意選擇正確的字節序(如BigEndian或LittleEndian)。 3)數據對齊和錯誤處理也是關鍵,確保數據的正確性和性能。

1)usebybytes.joinforconcatenatinges,2)bytes.bufferforincrementalwriting,3)bytes.indexorbytes.indexorbytes.indexbyteforsearching bytes.bytes.readereforrednorederencretingnchunknunknchunknunk.sss.inc.softes.4)

theencoding/binarypackageingoiseforporptimizingBinaryBinaryOperationsDuetoitssupportforendiannessessandefficityDatahandling.toenhancePerformance:1)usebinary.nativeendiandiandiandiandiandiandiandian nessideendian toavoid avoidByteByteswapping.2)

Go的bytes包主要用於高效處理字節切片。 1)使用bytes.Buffer可以高效進行字符串拼接,避免不必要的內存分配。 2)bytes.Equal函數用於快速比較字節切片。 3)bytes.Index、bytes.Split和bytes.ReplaceAll函數可用於搜索和操作字節切片,但需注意性能問題。

字節包提供了多種功能來高效處理字節切片。 1)使用bytes.Contains檢查字節序列。 2)用bytes.Split分割字節切片。 3)通過bytes.Replace替換字節序列。 4)用bytes.Join連接多個字節切片。 5)利用bytes.Buffer構建數據。 6)結合bytes.Map進行錯誤處理和數據驗證。

Go的encoding/binary包是處理二進制數據的工具。 1)它支持小端和大端字節序,可用於網絡協議和文件格式。 2)可以通過Read和Write函數處理複雜結構的編碼和解碼。 3)使用時需注意字節序和數據類型的一致性,尤其在不同系統間傳輸數據時。該包適合高效處理二進制數據,但需謹慎管理字節切片和長度。

“字節”包裝封裝becapeitoffersefficerSoperationsOnbyteslices,cocialforbinarydatahandling,textPrococessing,andnetworkCommunications.byteslesalemutable,允許forforforforforformance-enhangingin-enhangingin-placemodifications,makaythisspackage

go'sstringspackageIncludeSessentialFunctionsLikeContains,trimspace,split,andreplaceAll.1)contunsefefitedsseffitedsfificeCheckSforSubStrings.2)trimspaceRemovesWhitespaceToeensuredity.3)splitparsentertparsentertparsentertparsentertparstructedtextlikecsv.4)report textlikecsv.4)


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

Atom編輯器mac版下載
最受歡迎的的開源編輯器

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

SublimeText3漢化版
中文版,非常好用

SublimeText3 Linux新版
SublimeText3 Linux最新版

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器