如何使用 HTML 和 CSS 设置 Go 错误的样式?

How to style Go errors with HTML and CSS?

我想在我的 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 来设置我的错误页面的样式吗?

在执行模板之前,您可以手动编写您想要返回的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.