戈朗 : Send errors using Http Header

标签 go error-handling header http-headers

我想使用 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/

相关文章:

go - 如何用httprouter写测试

http - 如何将多个处理程序分配给同一个 uri?

ruby-on-rails - 在 Rails 应用程序上使用 Prawn gem 重复页脚与当前页面和每页的总页数,但重叠当前页码

c - 头文件与库

linux - 如何使用 GhostScript 避免标题截断 tiff。选择 于 tiff

mongodb - 从 mongodb 中提取嵌套结构数据

json - 存储和检索 RSA 加密 key

bash - 从 bash 脚本中启动的命令中检索错误代码

asp.net-mvc - 错误处理捕获 View 渲染异常的最后机会

mysql - #1005 - 无法使用 MySQL 创建表 'workswell_database.skoleni' 新手用户