1.Session:
Seesion是用户与计算机程序(通常是网络浏览器或移动程序)之间交互的一段时间.在此期间,用户执行的一系列由程序处理的操作或请求,程序会维护有关活动的状态信息.例如用户的身份 偏好和当前的Session数据.
2.Session作用:
保持用户登录状态:即使用户离开程序并稍后返回,仍能保持用户登录状态.
提供个性化体验:根据用户之前的交互和偏好,显示相关的内容或信息.
2.1demo:
go
package main
import (
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-gonic/gin"
)
func main() {
request := gin.Default()
//用secret进行加密.
store := cookie.NewStore([]byte("secret"))
request.Use(sessions.Sessions("mysession", store))
}
创建了一个基于Cookie的Session存储.并使用秘钥进行加密.
3.登录路由设置Session:
css
package main
import (
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
request := gin.Default()
request.POST("/login", func(c *gin.Context) {
userName := c.PostForm("username")
passWord := c.PostForm("password")
if userName != "" && passWord != "" {
session := sessions.Default(c)
session.Set("username", userName)
session.Save()
c.JSON(http.StatusOK, gin.H{"message":"登录成功"})
}else {
c.JSON(http.StatusNotFound, gin.H{"message":"未找到登录人"})
}
})
}
4.中间件校验Session:
go
func checkUserName() gin.HandlerFunc {
return func(c *gin.Context) {
userName := sessions.Default(c).Get("username")
if userName == nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"message": "未授权访问"})
return
}
c.Set("username", userName)
c.Next()
}
}
5.Redis存储Session:
go
package main
import (
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/redis"
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
request := gin.Default()
store, err := redis.NewStore(10, "tcp", "localhost:6379", "", "", []byte("secret"))
if err != nil {
panic(err)
}
request.Use(sessions.Sessions("mysession", store))
request.POST("/login", func(c *gin.Context) {
userName := c.PostForm("username")
password := c.PostForm("password")
if userName != "" || password != "" {
session := sessions.Default(c)
session.Set("username", userName)
session.Save()
c.JSON(http.StatusOK, gin.H{"message": "登录成功"})
} else {
c.JSON(http.StatusNotFound, gin.H{"message": "用户名错误"})
}
})
}
func checkUserName() gin.HandlerFunc {
return func(c *gin.Context) {
userName := sessions.Default(c).Get("username")
if userName == nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"message": "未授权访问"})
return
}
c.Set("username", userName)
c.Next()
}
}
上述代码中利用redis作为Session存储引擎.首先创建了一个具有十个连接池的Redis存储.连接到了位于localhost:6379的服务器,并使用秘钥进行了加密.