如何在http.ResponseWriter上设置HTTP状态代码 [英] How to set HTTP status code on http.ResponseWriter
问题描述
如何在 http.ResponseWriter
上设置HTTP状态代码(例如,设置为500或403)?
How do I set the HTTP status code on an http.ResponseWriter
(e.g. to 500 or 403)?
我可以看到请求通常附有状态码200.
I can see that requests normally have a status code of 200 attached to them.
推荐答案
使用 http.ResponseWriter.WriteHeader
.从文档中:
Use http.ResponseWriter.WriteHeader
. From the documentation:
WriteHeader发送带有状态代码的HTTP响应标头.如果未显式调用WriteHeader,则对Write的第一次调用将触发一个隐式WriteHeader(http.StatusOK).因此,对WriteHeader的显式调用主要用于发送错误代码.
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.
示例:
func ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500 - Something bad happened!"))
}
这篇关于如何在http.ResponseWriter上设置HTTP状态代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!