duanguilin2007 2017-08-24 19:41
浏览 418
已采纳

重定向返回http:多个响应.WriteHeader调用

I am using Jon Calhoun's Go MVC framework from github.

The framework uses julienschmidt/httprouter as its only dependency.

I have a similar main method as found in the example:

  func main() {
        //register routes
        router := httprouter.New()

        //default
        router.GET("/", controllers.Login.Perform(controllers.Login.Index))

        //login
        router.GET("/login", controllers.Login.Perform(controllers.Login.Login))
        router.POST("/login", controllers.Login.Perform(controllers.Login.PostLogin))

        //dashboard
        router.GET("/dashboard", controllers.Dashboard.Perform(controllers.Dashboard.Index))


        //listen and handle requests
        log.Fatal(http.ListenAndServe(":"+helpers.ReadConfig("port_http"), router))
    }

I make a post to the login url, and it calls the following method:

func (self LoginController) PostLogin(w http.ResponseWriter, r *http.Request, ps httprouter.Params) error {
    //create our api url
    var url = helpers.ReadConfig("api") + "login"
    //fill model to post
    login := models.LoginModel{
        Password: r.FormValue("password"),
        Email:    r.FormValue("username"),
    }
    //render json from model
    bytes, err := json.Marshal(login)
    if err != nil {
        panic(err)
    }
    //post to the API helpers
    var resp = helpers.ApiPost(url, r, string(bytes))
    //check response if successful
    if resp.Code != constants.ApiResp_Success {
        //TODO: Handle API Errors
        login.Password = ""
        errors := make(map[int]string)
        errors[1] = "Please provide valid credntials."
        login.Common = models.CommonModel{
            ErrorList: errors,
        }
        return views.Login.Index.Render(w, login, helpers.AcceptsGzip(r))
    }


    log.Println("---Redirect--")
    http.Redirect(w, r, "/dashboard", 307)
    log.Println("-----")
    return views.Dashboard.Index.Render(w, login, helpers.AcceptsGzip(r))
}

Basically, if the login was not correct I return the same view. If the login is correct I want to redirect to another method in a different controller.

However when I call http.Redirect(w, r, "/dashboard", 307), it returns the following error:

http: multiple response.WriteHeader calls  

I'm not sure exactly why this is happening, but I suspect that it has something to do with my listener calling the Perform function, which creates a http.handler, as shown below.

func (c *Controller) Perform(a Action) httprouter.Handle {
    return httprouter.Handle(
        func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
            //set response headers
            //TODO: set appropriate responce headers
            w.Header().Set("Access-Control-Allow-Origin", "*")
            w.Header().Set("Cache-Control", "public, max-age=0")
            w.Header().Set("Token", "NOT-A-VALID-TOKEN")
            w.WriteHeader(200)
            if err := a(w, r, ps); err != nil {
                http.Error(w, err.Error(), http.StatusInternalServerError)
            }

        })
}

Does anyone have any idea how to redirect using this MVC framework? Or have a one off solution?

  • 写回答

1条回答

  • dsw8292301 2017-08-24 20:22
    关注

    http.ResponseWriter's WriteHeader method can only be called once per HTTP response, for obvious reasons: You can only have a single response code, and you can only send the headers once.

    The error you see means that it is called a second time on the same response.

    Your middleware calls:

            w.WriteHeader(200)
    

    Then your handler also calls:

    http.Redirect(w, r, "/dashboard", 307)
    log.Println("-----")
    return views.Dashboard.Index.Render(w, login, helpers.AcceptsGzip(r))
    

    Your middleware should never call WriteHeader, until after the fate of the response is known.

    Further, without knowing about your particular MVC framework, it seems possible that after you send the 307 status, then you also tell the MVC framework to render a response, which may also call WriteHeader again.

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

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大