英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论