[英]Go multiple response.WriteHeader calls
So I'm writing a basic webapp and I'm having trouble redirecting the user after a sucessfull login. 因此,我正在编写一个基本的Web应用程序,并且在成功登录后无法重定向用户。 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". 错误消息是:“ http:多个response.WriteHeader调用”。
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. 我的问题是,在不调用设置标头的t.Execute的情况下,我看不到提供包含登录表单的html文件的方法。
How can I display the login page and still be able to redirect to a different page? 如何显示登录页面并且仍然能够重定向到其他页面?
You are writing (using w
) and then later trying to redirect (also using w
) using 302
header redirection. 您正在编写(使用
w
),然后稍后尝试使用302
标头重定向进行重定向(也使用w
)。
You can only send headers once, and if you start writing to w it assumes a 200
header (OK) 您只能发送一次标头,并且如果您开始写入w,它将假定标头为
200
(确定)
Also, Its best if you check the http.Method before writing to the ResponseWriter ( w
) 另外,最好在写入ResponseWriter(
w
)前检查http.Method
And, Remember to return
after a redirection or handing over the ResponseWriter and Request pair to another function! 而且,记住要
return
重定向或移交ResponseWriter并请求对另一功能之后!
Hope this helps. 希望这可以帮助。
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: 您的Go主程序:
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.
您可以在查询字符串中传递一个参数,该参数包含重定向的目标路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.