golang web 实现浴室预约方案 使用session管理用户登录权限

golang web 开发 实现校园浴室预约方案

登陆验证模块

实体类

//Student 学生实体类
type Student struct {
   
	ID        int
	StudentID string
	Password  string
	Name      string
}

//Room 浴室实体类
type Room struct {
   
	ID   int
	Type string
}
//Logstr 记录信息
type Logstr struct {
   
	ID        int
	StudentID string
	RoomID    string
	Type      string
	TimeStr   string
	EndTime   string
}
index.html
<!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" type="text/css" href="/static/layui/css/layui.css">
    <script type="text/javascript" src="/static/layui/layui.js"></script>
    <script type="text/javascript" src="/static/js/jquery-3.4.1.js"></script>
    <title></title>
</head>

<body>
    <form action="/login" method="POST">
        <p>学号<input type="text" id="studentid" name = "studentid" value=""/></p>
        <p>密码<input type="text" id="password" name = "password" value=""/></p>
        <input type="submit" id="but1" value="提交" />
    </form>
    <p><b> {
   {
   .}}</b></P>
</body>

</html>
建立web服务
const (
	countTotalRoomSQL             = "select count(*) from room"
	countOccupyRoomSQL            = "select count(*) from room where type ='0'  "
	findRoomSQL                   = "select * from room where  type ='0'"
	updateRoomSQL                 = "update room set type = $1 where id = $2"
	insertLogSQL                  = "insert into log (student_id,room_id,type,timestr,end_time) values($1,$2,$3,$4,$5) returning id"
	updateLogSQL                  = "update log set type = '0' where student_id  = $1 and type = '1'"
	findLogSQL                    = "select room_id from log where type = '1' and student_id = $1"
	clearLogSQL                   = "update log set type= '0' where end_time <now() and type = '1' returning room_id"
	findRoomByTypeAndStudentIDSQL = "select id,timestr from log where student_id=$1 and type = '1'"
	//查找对象语句
	selectSQL = "select * from student where student_id = $1 and password = $2"
)

var (
	sessionMgr *SessionMgr = nil //session管理器
	mu         sync.Mutex
)

func init() {
   
	sessionMgr = NewSessionMgr("TestCookieName", 3600)
}

func HTTPTest() {
   
	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
	http.HandleFunc("/login", login)
	http.HandleFunc("/index", addpHanderFunc(index))
	http.HandleFunc("/success", addpHanderFunc(success))
	http.HandleFunc("/exitRoom", addpHanderFunc(exitRoom))
	err := http.ListenAndServe("localhost:8080", nil)
	if err != nil {
   
		fmt.Println(err)
	}
}
//将验证用户是否登陆包装到路由中
func addpHanderFunc(a http.HandlerFunc) http.HandlerFunc {
   
	return func(w http.ResponseWriter, r *http.Request) {
   
		if testToken(w, r) {
   
			a(w, r)
		}
	}
}
登陆验证方法

index 方法 以及接收前端账号密码 验证返回页面


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

	var (
		viewEntity View1
		Entity     View2
	)
	//这里是判断用户之前有没有预约的数据如果有直接进入预约成功的界面
	loginUser := getLoginUser(w, r)
	DB.QueryRow(findRoomByTypeAndStudentIDSQL, loginUser.StudentID).Scan(&Entity.Number, &Entity.TimeStr)
	if Entity.Number != "" && Entity.TimeStr != "" {
   
		tmpl, err := template.ParseFiles("view/success.html")
		if err != nil {
   
			fmt.Println(err)
		}
		tmpl.Execute(w, Entity)
		return
	}
	fmt.Println("登陆成功这是登陆用户", getLoginUser(w, r))
	t, err := template.ParseFiles("view/index.html")
	if err != nil {
   
		Mylog.Println(err)
	}
	viewEntity.Count = Count()
	t.Execute(w, viewEntity)
}

//处理登录
func login(w http.ResponseWriter, r *http.Request) {
   
	if r.Method == "GET" {
   
		fmt.Println("请求到了登陆页面")
		t, _ := template.ParseFiles("view/login.html")
		t.Execute(w, nil)

	} else if r.Method == "POST" {
   
		fmt.Println("请求到了验证")
		//请求的是登陆数据,那么执行登陆的逻辑判断
		r.ParseForm()

		//可以使用template.HTMLEscapeString()来避免用户进行js注入
		var student Student
		studentid := r.FormValue
好的,这里给你一个简单的 Go 语言实现 session 的多用户登录的例子: ```go package main import ( "fmt" "net/http" "github.com/gorilla/sessions" ) type User struct { username string password string } var users = []User{ {"user1", "password1"}, {"user2", "password2"}, {"user3", "password3"}, } var store = sessions.NewCookieStore([]byte("secret")) func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { // 获取 session session, err := store.Get(r, "session-name") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // 检查是否已经登录 if username, ok := session.Values["username"].(string); ok { fmt.Fprintf(w, "欢迎 %s 登录!", username) return } // 如果未登录,则显示登录界面 fmt.Fprint(w, ` <form method="POST" action="/login"> <label>用户名:</label> <input type="text" name="username"><br> <label>密码:</label> <input type="password" name="password"><br> <input type="submit" value="登录"> </form> `) }) http.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) { // 获取 session session, err := store.Get(r, "session-name") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // 获取表单数据 username := r.FormValue("username") password := r.FormValue("password") // 遍历用户列表,验证用户名和密码是否匹配 for _, user := range users { if user.username == username && user.password == password { // 登录成功,将用户名保存到 session 中,并跳转到首页 session.Values["username"] = username session.Save(r, w) http.Redirect(w, r, "/", http.StatusFound) return } } // 登录失败,重新显示登录界面 fmt.Fprint(w, ` <p>用户名或密码不正确,请重新登录。</p> <form method="POST" action="/login"> <label>用户名:</label> <input type="text" name="username"><br> <label>密码:</label> <input type="password" name="password"><br> <input type="submit" value="登录"> </form> `) }) http.ListenAndServe(":8080", nil) } ``` 以上代码使用了 Gorilla 的 sessions 包来实现 session 功能。在首页中,会先获取 session,然后检查是否已经登录,如果已经登录,则输出欢迎信息;否则显示登录界面。在登录接口中,会先获取表单数据,然后遍历用户列表,逐个验证用户名和密码是否匹配。如果登录成功,则将用户名保存到 session 中,并跳转到首页;否则重新显示登录界面。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值