1、首先在templates文件夹下建立login.html。
<form class="form form-horizontal" action="/login" method="post">
<div class="row cl">
<label class="form-label col-xs-3"><i class="Hui-iconfont"></i></label>
<div class="formControls col-xs-8">
<input id="username" name="username" type="text" placeholder="账户" class="input-text size-L">
</div>
</div>
<div class="row cl">
<label class="form-label col-xs-3"><i class="Hui-iconfont"></i></label>
<div class="formControls col-xs-8">
<input id="password" name="password" type="password" placeholder="密码" class="input-text size-L">
</div>
</div>
{{.}}
<div class="row cl">
<div class="formControls col-xs-8 col-xs-offset-3">
<input name="" type="submit" class="btn btn-success radius size-L" value=" 登 录 ">
<input name="" type="reset" class="btn btn-default radius size-L" value=" 取 消 ">
</div>
</div>
</form>
在server.go文件中有以下内容
r.HandleFunc("/", web.Index)
r.HandleFunc("/login", web.Login).Methods("POST")
访问http://localhost:9091时,会执行web.Inedx方法
此方法会转向到login.html页面
func Index(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html;charset=utf-8")
t, _ := template.ParseFiles("templates/login.html")
t.Execute(w, nil)
}
func Login(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html;charset=utf-8")
username := r.PostFormValue("username")
password := r.PostFormValue("password")
user, err := dbdata.Login(username, password)
if err != nil {
t, _ := template.ParseFiles("templates/login.html")
t.Execute(w, "数据库链接失败")
}
if user.Username != "" {
uservo := new(utils.Uservo)
uservo.Id = user.Id
uservo.Realname = user.Realname
uservo.Username = user.Username
tokenstring := utils.SetToken(*uservo)
uservo.Token = tokenstring
SetCookie(w, r, tokenstring)
t, _ := template.ParseFiles("templates/index.html")
t.Execute(w, nil)
} else {
t, _ := template.ParseFiles("templates/login.html")
t.Execute(w, "用户密码错误")
}
}