donpb2823 2015-07-06 06:17
浏览 40
已采纳

Golang:使用Http标头发送错误

I want to send all the errors that I get to another service(Consume my service) using Http Header

Ex: I tried this but it doesn't work:

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)
          }
  }

if I give a valide template I got "successfull" : "A Go Web Server" on the Header, but if I give no existing tempalte I got 502 Bad Gateway and this on the 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

I want to know if there is a way to send the Error that i got through a header, I mean templates/VastPlayer/TempVide_.txt: no such file or directory

Thank you in advance

展开全部

  • 写回答

1条回答 默认 最新

  • doutui9606 2015-07-06 07:38
    关注

    The 502 response, is coming from nginx, so first test the go server directly on port 6001. Also, look at the output for your server's process, there error will be printed there.

    After you set your error header and call http.Error you need a return, otherwise you're going to continue executing the rest of the handler. Since tmpl is nil if there was an error, calling tmpl.Execute causes a nil pointer dereference, and the server panics.

    (And you start out setting a "successful" header, so that will always be there, even if there's an error.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部