[實作] 從零開始用 Golang 寫網頁 : 06 加入錯誤頁面
通常網頁伺服器或框架本身會內建錯誤通知頁面給使用者,但通常會暴露許多技術細節,所以要上線的網頁程式必須提供自己的錯誤頁面
1 2 3 4 5 6 7 8 9 10 11
   | func notFound(w http.ResponseWriter, r *http.Request) { 	w.WriteHeader(http.StatusNotFound)
  	t, err := template.ParseFiles("./templates/errorpage/NotFoundPage.html")
  	if err != nil { 		fmt.Println("NotFoundPage開啟錯誤 : ", err) 	}
  	t.Execute(w, nil) }
  | 
 
1 2 3 4 5 6 7 8 9 10 11
   | func errHandler(w http.ResponseWriter, r *http.Request, p interface{}) { 	w.WriteHeader(http.StatusInternalServerError)
  	t, err := template.ParseFiles("./templates/errorpage/ServerErrorPage.html")
  	if err != nil { 		fmt.Println("ServerErrorPage開啟錯誤 : ", err) 	}
  	t.Execute(w, nil) }
  | 
 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
   | func main() {
  	mux := httprouter.New()
  	mux.GET("/", index) 	mux.GET("/:name", hello)
  	mux.NotFound = http.HandlerFunc(notFound)
  	mux.PanicHandler = errHandler
  	
  	fmt.Println("服務器即將開啟, 訪問地址 http://localhost:8080")
  	server := http.Server{ 		Addr:    ":8080", 		Handler: mux, 	}
  	err := server.ListenAndServe()
  	if err != nil { 		fmt.Println("服務器開啟錯誤 : ", err) 	} }
  | 
 
notFound、errHandler
main
- 這邊指定 
mux.NotFound 與 mux.PanicHandler 兩個事件的處理器 
結果
