如何在http.ResponseWriter上设置HTTP状态代码


102

如何在上设置HTTP状态代码http.ResponseWriter(例如,设置为500或403)?

我可以看到请求通常附有状态码200。

Answers:


165

使用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!"))
}

如何访问包含在中间件中的标头。res.Header()。Get('StatusCode')给出nil。
kailash yogeshwar

92

除了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()方法是您的朋友


我不知道为什么,但是只有这个答案对我有用,而不是“ WriteHeader(int)”,所以谢谢很多!
Wishmaster

31
w.WriteHeader(http.StatusInternalServerError)
w.WriteHeader(http.StatusForbidden)

完整清单在这里


2
它记录http: superfluous response.WriteHeader call
panchicore

2
嘿@panchicore,以防事后看来不明显-为了完整起见-您只能发送一个这样的标头,第二个只是另一个示例。该警告中的“多余”仅表示应仅发送第一个。
亚当·杰克
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.