进行多个响应.WriteHeader调用

因此,我正在编写一个基本的Web应用程序,但在成功登录后无法重定向用户。 代码是:</ p>

  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()
用户:= r.FormValue(“用户名”)
通过:= r.FormValue(“ password”)

如果checkLogin(user ,pass){
loginIn = true
http.Redirect(w,r,“ / home”,302)
}
}
</ code> </ pre>

错误消息是:“ http:多个响应。WriteHeader调用”。</ p>

我的问题是,我不找到一种无需调用t即可提供包含登录表单的html文件的方法。 执行,设置标题。</ p>

如何显示登录页面,仍然能够重定向到其他页面? </ p>
</ div>

展开原文

原文

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?

dra11767
dra11767 您可以发布Execute方法吗?
大约 2 年之前 回复

2个回答

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

Have a different route for authentication. Make the login form submit to the authentication route. Have a separate handler for authentication as well.

For example, your login form:

<form method="post" action="/auth">

your Go main:

http.HandleFunc("/", homeHandler)
http.HandleFunc("/auth", authHandler)

When authentication processing is complete you can redirect the user to the appropriate page. You could pass a parameter in the query string that contains the destination path for the redirect.

dongxiaoke2018
dongxiaoke2018 这很好。 谢谢!
大约 2 年之前 回复



您正在写(使用 w </ code>),后来又尝试重定向(也使用 w < / code>)使用 302 </ code>标头重定向。</ p>

您只能发送标头一次,并且如果您开始写入w,它将假定 200 </ code>标头(OK)</ p>

此外,最好的做法是,在写入ResponseWriter( w </ code>)</ p>
\之前检查http.Method n

而且,切记在重定向后将 return </ code>或将ResponseWriter和Request对移交给另一个函数!</ p>

希望这会有所帮助。</ p>

</ div>

展开原文

原文

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.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问