我想在我的 Go Web 應用程序中設置錯誤樣式。目前我正在處理類似以下示例的錯誤:if !ok { http.Error(w, "Username and/or password do not match", http.StatusForbidden) return}但是,這會導致錯誤消息在瀏覽器中顯示為簡單文本。我想用 HTML 和 CSS 來設置我的錯誤樣式,但簡單地忽略該http.Error方法并使用似乎是不好的做法:TPL := template.Must(template.ParseGlob("templates/*.gohtml"))if !ok { TPL.ExecuteTemplate(w, "usernamePasswordMismatch.gohtml", nil)}有人可以推薦一種方法來正確處理我的錯誤,使用該http.Error方法或類似的方法,并且仍然使用 HTML 和 CSS 設計我的錯誤頁面嗎?
1 回答

qq_遁去的一_1
TA貢獻1725條經驗 獲得超8個贊
在執行模板之前,您可以手動編寫w.WriteHeader
您想要返回的http狀態代碼:
TPL := template.Must(template.ParseGlob("templates/*.gohtml"))
if !ok {
? ? w.WriteHeader(http.StatusForbidden)
? ? TPL.ExecuteTemplate(w, "usernamePasswordMismatch.gohtml", nil)
}
您需要WriteHeader在寫入實際數據之前調用,否則ResponseWriter將自動用作StatusOK響應:
// If WriteHeader has not yet been called, Write calls
// WriteHeader(http.StatusOK) before writing the data.
- 1 回答
- 0 關注
- 142 瀏覽
添加回答
舉報
0/150
提交
取消