doupeng5320 2018-06-23 21:04
浏览 136

进行多个响应.WriteHeader调用

So I'm writing a basic webapp and I'm having trouble redirecting the user after a sucessfull login. The code is:

t, err := template.ParseFiles("home.html")
if err != nil {
    log.Fatal("template.ParseFiles: ", err)
}

err = t.Execute(w, nil)
if err != nil {
    log.Fatal("t.Execute: ", err)
}

if r.Method == "POST" {
    r.ParseForm()
    user := r.FormValue("username")
    pass := r.FormValue("password")

    if checkLogin(user, pass) {
        loggedIn = true
        http.Redirect(w, r, "/home", 302)
    }
}

The error message is: "http: multiple response.WriteHeader calls".

My problem is that I don't see a way to serve the html file containing the login-form without calling t.Execute which sets the header.

How can I display the login page and still be able to redirect to a different page?

  • 写回答

2条回答

  • duandongji2231 2018-06-23 23:50
    关注

    You are writing (using w) and then later trying to redirect (also using w) using 302 header redirection.

    You can only send headers once, and if you start writing to w it assumes a 200 header (OK)

    Also, Its best if you check the http.Method before writing to the ResponseWriter (w)

    And, Remember to return after a redirection or handing over the ResponseWriter and Request pair to another function!

    Hope this helps.

    评论

报告相同问题?

悬赏问题

  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口