如何在上设置HTTP状态代码http.ResponseWriter
(例如,设置为500或403)?
我可以看到请求通常附有状态码200。
Answers:
使用http.ResponseWriter.WriteHeader
。从文档中:
WriteHeader发送带有状态代码的HTTP响应标头。如果未显式调用WriteHeader,则对Write的第一次调用将触发一个隐式WriteHeader(http.StatusOK)。因此,对WriteHeader的显式调用主要用于发送错误代码。
例:
func ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500 - Something bad happened!"))
}
除了WriteHeader(int)
可以使用辅助方法http.Error之外,例如:
func yourFuncHandler(w http.ResponseWriter, r *http.Request) {
http.Error(w, "my own error message", http.StatusForbidden)
// or using the default message error
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
}
http.Error()和http.StatusText()方法是您的朋友
w.WriteHeader(http.StatusInternalServerError)
w.WriteHeader(http.StatusForbidden)
完整清单在这里
http: superfluous response.WriteHeader call