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

Nic*_*k H 79 go

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

我可以看到请求通常附加了200的状态代码.

Tim*_*per 130

使用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!"))
}
Run Code Online (Sandbox Code Playgroud)

  • 如何访问封装中间件中写入的标头。res.Header().Get('StatusCode') 给出 nil。 (2认同)

Yan*_*ozo 69

除了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)
}
Run Code Online (Sandbox Code Playgroud)

http.Error()和http.StatusText()方法是你的朋友


Mar*_*ovy 24

w.WriteHeader(http.StatusInternalServerError)
w.WriteHeader(http.StatusForbidden)
Run Code Online (Sandbox Code Playgroud)

完整列表在这里

  • 嘿@panchicore,以防事后看来并不明显 - 为了完成 - 你只能发送一个这样的标头,第二个只是一个不同的例子。该警告中的“多余”仅表明仅应发送第一个警告。 (5认同)
  • 它记录“http:多余的响应。WriteHeader 调用” (2认同)
  • @panchicore 如果未显式调用“WriteHeader”,则第一次调用“Write”将触发隐式“WriteHeader(http.StatusOK)”。确保在“Write”之前调用“WriteHeader”。 (2认同)