我想使用 Http Header 将我得到的所有错误发送到另一个服务(使用我的服务)
例如:我试过了,但它不起作用:
func main() {
http.HandleFunc("/", foo)
log.Println("Listening...")
http.ListenAndServe(":6001", nil)
}
func foo(w http.ResponseWriter, r *http.Request) {
w.Header().Set("successfull", "A Go Web Server")
fi := path.Join("templates/VastPlayer", "TempVide_.txt")
tmpl, err := template.ParseFiles(fi)
if err != nil {
w.Header().Set("Error", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
}
if err := tmpl.Execute(w, ""); err != nil{
w.Header().Set("Error", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
如果我提供一个有效的模板,我会在标题上得到 "successfull": "A Go Web Server",但是如果我没有提供现有的模板,我会得到 502 Bad Gateway 这个在标题上
HTTP/1.1 502 Bad Gateway
Server: nginx/1.8.0
Date: Mon, 06 Jul 2015 15:19:31 GMT
Content-Type: text/html
Content-Length: 574
Connection: keep-alive
我想知道是否有办法发送我通过 header 获得的错误, 我是说 templates/VastPlayer/TempVide_.txt: no such file or directory
提前致谢
最佳答案
502
响应来自 nginx,所以首先直接在端口 6001 上测试 go 服务器。另外,查看服务器进程的输出,那里会打印错误。
设置错误 header 并调用 http.Error
后,您需要一个 return
,否则您将继续执行处理程序的其余部分。由于如果出现错误,tmpl
为 nil,因此调用 tmpl.Execute
会导致 nil 指针取消引用,并且服务器出现困惑。
(你开始设置一个“成功”的标题,这样它就会一直存在,即使有错误。)
关于戈朗 : Send errors using Http Header,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31248242/