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.

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

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀