donpb2823 2015-07-06 14: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 15: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.)

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

报告相同问题?

悬赏问题

  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答