0

I want to redirect to homepage after successful logging in and I'm generating the HTML for the homepage using go HTML-template. When I login the url does change to /home and the HTML page loads too. But it doesn't load the page variables passed from server-side.

func LoginHandler(w http.ResponseWriter, r *http.Request) {
....

PageVars := Login{
    Username: username,
}
http.Redirect(w,r,"/home",302) 
t, err := template.ParseFiles("static/home.html")
if err != nil {  
    log.Printf("template parsing error: ", err)
}

err = t.Execute(w, PageVars)

if err != nil { 
    log.Printf("template executing error: ", err)
}


}

my html page is as follows:

<!DOCTYPE html> 
<html>
<body>
    <div id="mainContainer" class="alignCenter">
            <header class = "nav">
                <div class = "nav-links">
                    <span class="headerTitle" id="headerTitle">{{.Username}}</span>
                    <form action="http://localhost:8080/api/logout" method="POST">
                         <span id="logout" onclick="document.forms[0].submit()">Logout</span>
                    </form>
                </div>
            </header>

    </div>
</body>

After logging-in, the page displays {{.Username}} in the header and not the logged-in username from server-side.

If I place the http.Redirect(w,r,"/home",302) after template execution, the username loads but the url directs to the api call, like this http://localhost:8080/api/login instead of http://localhost:8080/home. I've been coding go only since two days now. What am I doing the wrong way here, please help.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Anjali
  • 73
  • 3
  • 4
  • 13
  • 1
    `/home` should be served by a separate handler from the login one. LoginHandler should log in the user, create and set a cookie session, redirect and return (no rendering necessary). The HomeHandler should retrieve the session, retrieve the user info associated with the session, and then render the home page. – mkopriva Jun 04 '19 at 06:43
  • The `PageVars`just happened to be named by you that way. It is the [context for the template engine](https://stackoverflow.com/questions/23260821/what-is-apache-velocity/23261610#23261610), and will cease to exist after the handler finished. What you want are [session variables](https://stackoverflow.com/a/35292106/1296707). – Markus W Mahlberg Jun 04 '19 at 23:44
  • Thanks for the clarity. I updated your title, too. – Jonathan Hall Jun 05 '19 at 07:51

0 Answers0