Go 如何在HTTP.ResponseWriter上设置HTTP状态代码
如何在Go 如何在HTTP.ResponseWriter上设置HTTP状态代码,go,Go,如何在HTTP.ResponseWriter上设置HTTP状态代码(例如设置为500或403) 我可以看到请求通常附加了200的状态代码。使用。从文件中: WriteHeader发送带有状态代码的HTTP响应头。如果未显式调用WriteHeader,则对Write的第一个调用将触发隐式WriteHeader(http.StatusOK)。因此,对WriteHeader的显式调用主要用于发送错误代码 例如: func ServeHTTP(w http.ResponseWriter, r *http
HTTP.ResponseWriter
上设置HTTP状态代码(例如设置为500或403)
我可以看到请求通常附加了200的状态代码。使用。从文件中:
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)
之外,您还可以使用helper方法,例如:
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()和方法是您的朋友我不知道为什么,但只有这个答案对我有效,而不是“WriteHeader(int)”,所以thanx很多!它记录了
http:superfluous response.WriteHeader call
Hey@panchicore,以防事后发现它不明显——并且为了完成——您只能发送一个这样的头,第二个只是一个不同的示例。该警告中的“多余”仅表示只应发送第一个消息。如何访问在封闭中间件中编写的头文件。res.Header().Get('StatusCode')给出nil。
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)
}