dtxb75622 2019-06-04 03:07
浏览 123

使用http.Redirect重定向到使用html模板生成的网页

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.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 安卓adb backup备份应用数据失败
    • ¥15 eclipse运行项目时遇到的问题
    • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
    • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
    • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
    • ¥50 成都蓉城足球俱乐部小程序抢票
    • ¥15 yolov7训练自己的数据集
    • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
    • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
    • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)