利用cookie记录用户名密码登录
cookie 操作
// 设置 cookie, 函数的第一个参数是 key 值,第二个参数是设置的 value 值 ,第三个参数是这个Cookie的有效时间
this.Ctx.SetCookie("key", value, time)
// 获取 cookie ,函数参数就是 key 值,返回值是对应的 value
this.Ctx.GetCookie("key")
Session 存储在服务器端
Cookie 存储在浏览器端
记住用户名密码控制器 HandleLogin()
增加 设置记住用户名以下代码
// 登录页面 post
func (this *LoginController) HandleLogin() {
// 设置记住用户名
check := this.GetString("remember")
// 判断是否选择记住用户名密码
if check == "on" {
// 设置cookie ,时间一小时
this.Ctx.SetCookie("Name", Name, time.Second*60*60)
this.Ctx.SetCookie("Pwd", Pwd, time.Second*60*60)
}else {
// 设置cookie ,负数为不记录
this.Ctx.SetCookie("Name", Name, -1)
this.Ctx.SetCookie("Pwd", Pwd, -1)
}
// 实际情况注册成功返回到登录页面
this.Redirect("index", 302)
}
显示用户名密码控制器 ShowLogin()
// 登录页面 get
func (this *LoginController) ShowLogin() {
// 获取 cookie
name := this.Ctx.GetCookie("Name")
pwd := this.Ctx.GetCookie("Pwd")
// 判断是否能获取到cookie,然后传递到视图
if name != "" || pwd != ""{
this.Data["UserName"] = name
this.Data["PassWord"] = pwd
this.Data["Checked"] = "checked"
}else{
this.Data["UserName"] = ""
this.Data["PassWord"] = ""
}
this.TplName = "login.html"
}
html 页面
login.html 增加以下
value="{{.UserName}}"
value="{{.PassWord}}"
{{.Checked}}
<form class="login_form" name = "login" action="/login" method="post">
<h1 class="login_title">用户登录</h1>
<input type="text" class="input_txt" name = "userName" value="{{.UserName}}">
<input type="password" name = "passWord" value="{{.PassWord}}" class="input_txt">
<div class="remember"><input type="checkbox" name="remember" {{.Checked}} ><label>记住用户名</label></div>
<input type="submit" value="登 录" class="input_sub">
<span>{{.errmsg}}</span>
</form>