一.登录功能流程图
- 用户登录后判断帐号和密码是否正确,其中帐号可以是用户名、电话、邮箱.
- 服务器端判断后返回EgoResult结构体对应的JSON数据,其中Status=200表示成功,成功后页面跳转到
/index
,Status只要不为200都表示登录失败,页面给出提示框告诉用户登录失败 - 流程图
二.登录代码实现
- 在src下新建user目录
- 在user下新建TbUser.go文件,编写实体
package user
//对应数据库中用户表
type TbUser struct {
//属性首字母大写:1. 要转换为json 2. 可能出现跨包访问
Id int64
Username string
Password string
Phone string
Email string
Created string
Updated string
}
- 在user下新建TbUserDao.go文件,编写数据访问代码
package user
import (
"commons"
"fmt"
)
//根据用户名和密码查询,如果返回值为nil表示查询失败,否则成功
func SelByUnPwdDao(un, pwd string) *TbUser{
sql := "select * from tb_user where username=? and password=? or email=? and password=? or phone=? and password=?"
rows,err:=commons.Dql(sql, un, pwd, un, pwd, un, pwd)
if err!=nil{
fmt.Println(err)
return nil
}
if rows.Next(){
user:=new(TbUser)
rows.Scan(&user.Id,&user.Username,&user.Password,&user.Phone,&user.Email,&user.Created,&user.Updated)
commons.CloseConn()
return user
}
return nil
}
- 在user下新建TbUserService.go 编写业务逻辑代码
package user
import "commons"
func LoginService(un,pwd string) (er commons.EgoResult){
u:=SelByUnPwdDao(un,pwd)
if u!=nil{
er.Status=200
}else{
er.Status=400
}
return
}
- 在user下新建TbUserController.go编写控制器代码
package user
import (
"net/http"
"encoding/json"
)
//所有user模块的handler
func UserHandler() {
http.HandleFunc("/login", loginController)
}
//登录
func loginController(w http.ResponseWriter, r *http.Request) {
username := r.FormValue("username")
password := r.FormValue("password")
er := LoginService(username, password)
//把结构体转换为json数据
b, _ := json.Marshal(er)
//设置响应内容为json
w.Header().Set("Content-Type", "application/json;charset=utf-8")
w.Write(b)
}
- 在main.go中引用UserHandler()让user模块所有控制器生效
func main() {
s := http.Server{Addr: ":80"}
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
http.HandleFunc("/", welcome)
//用户相关
user.UserHandler()
s.ListenAndServe()
}