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?
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.