Golang:使用 Http 发送错误 Header

Golang: Send errors using Http Header

我想使用 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" on the Header,但如果我没有给出现有的模板,我得到 502 Bad Gateway 并且在 header

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: 没有那个文件或目录

提前致谢

502 响应来自 nginx,所以首先直接在端口 6001 上测试 go 服务器。另外,查看服务器进程的输出,那里会打印错误。

设置错误 header 并调用 http.Error 后,您需要一个 return,否则您将继续执行处理程序的其余部分。由于如果出现错误 tmpl 为 nil,调用 tmpl.Execute 会导致 nil 指针取消引用,并且服务器出现混乱。

(并且您开始设置 "successful" header,这样即使出现错误,它也会一直存在。)