如何在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)
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)
完整列表在这里