doushu0591 2015-10-20 14:35
浏览 146

在Go中从前端向后端提交数据

I have simple website. Go with JavaScript. Now I get this message "http: multiple response.WriteHeader calls" and I know that a have another header open. But I don't know where and I'm struggling to find a solution.

func (t *Server) RootHandler(w http.ResponseWriter, r *http.Request) {
    var c *entities.Korisnik
    var k *entities.Kilometri
    var a *entities.Auto

    if c = t.authentication(w, r); c == nil {
        return
    }

    gk, err := t.store.GetKilometri(c)

    if errorEval(w, err, http.StatusInternalServerError) {
        return
    }
    if err := r.ParseForm(); err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    if r.FormValue("debug") == "true" {
        s, _ := json.MarshalIndent(&Bla{c, gk}, "", "    ")
        w.Write(s)
        return
    } else {
        w.Header().Set("Content-Type", "application/json")
        errorEval(w, json.NewEncoder(w).Encode(&Bla{c, gk}), http.StatusInternalServerError)

    }

    log.Println("0")
    if errorEval(w, json.NewDecoder(r.Body).Decode(&Input{a, k}), http.StatusBadRequest) {
        log.Println("1")
        return
    }
    err = t.store.NewKilometri(k, c, a)
    log.Println("2")
    if errorEval(w, err, http.StatusInternalServerError) {
        return

    }
}

I get this in my terminal

015/10/20 16:12:32 0
2015/10/20 16:12:32 EOF
2015/10/20 16:12:32 http: multiple response.WriteHeader calls
2015/10/20 16:12:32 1
2015/10/20 16:12:32 0
2015/10/20 16:12:32 EOF
2015/10/20 16:12:32 http: multiple response.WriteHeader calls
2015/10/20 16:12:32 1

func errorEval(w http.ResponseWriter, err error, status int) bool {
if err == nil {
    return false
}
log.Println(err)
http.Error(w, errorString[status], status)
return true

}

  • 写回答

1条回答 默认 最新

  • dongshan6870 2015-10-20 14:45
    关注

    It looks to me like errorEval likely writes the status code and maybe a body if an error is encountered. Most places you call it you check the return and return from your handler if it handles an error.

    In the case of errorEval(w, json.NewEncoder(w).Encode(&Bla{c, gk}), http.StatusInternalServerError) you are not checking the return.

    My guess is, there is some json error and the handler is writing a 500 response, and you are continuing to do other things which in turn try to write additional responses.

    评论

报告相同问题?

悬赏问题

  • ¥15 MATLAB动图的问题
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名