How do you execute a template with 500 status code in Go?

huangapple go评论80阅读模式
英文:

How do you execute a template with 500 status code in Go?

问题

我知道可以使用以下代码执行模板:

t.ParseFiles(name)
t.Execute(w, page)

并且可以使用以下代码返回500状态码,并携带类似的错误信息:

http.Error(w, err.Error(), http.StatusInternalServerError)

但是,如果要返回一个包含该错误信息的模板,应该如何处理呢?

英文:

I know that I can execute template with:

t.ParseFiles(name)
t.Execute(w, page)

And respond 500 with a message like this:

http.Error(w, err.Error(), http.StatusInternalServerError)

But how should I return 500 with a template that contains that message?

答案1

得分: 5

在执行模板之前,请调用ResponseWriter.WriteHeader

> WriteHeader用于发送带有状态码的HTTP响应头。
> 如果没有显式调用WriteHeader,第一次调用Write将触发隐式的WriteHeader(http.StatusOK)。
> 因此,显式调用WriteHeader主要用于发送错误代码。

t.ParseFiles(name)
w.WriteHeader(http.StatusInternalServerError)
t.Execute(w, page)

如果你查看http.Error的源代码,你会发现它做了同样的事情。

英文:

Call ResponseWriter.WriteHeader before you execute your template:

> WriteHeader sends an HTTP response header with status code.
> If WriteHeader is not called explicitly, the first call to Write
> will trigger an implicit WriteHeader(http.StatusOK).
> Thus explicit calls to WriteHeader are mainly used to send error codes.

t.ParseFiles(name)
w.WriteHeader(http.StatusInternalServerError)
t.Execute(w, page)

If you look at the source code of http.Error, you can see it's doing the same thing.

huangapple
  • 本文由 发表于 2017年3月26日 02:25:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/43020241.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定