Gin处理Session的实现
1.Session:
Seesion是用户与计算机程序(通常是网络浏览器或移动程序)之间交互的一段时间.在此期间,用户执行的一系列由程序处理的操作或请求,程序会维护有关活动的状态信息.例如用户的身份 偏好和当前的Session数据.
2.Session作用:
保持用户登录状态:即使用户离开程序并稍后返回,仍能保持用户登录状态.
提供个性化体验:根据用户之前的交互和偏好,显示相关的内容或信息.
2.1demo:
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:
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:
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:
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的服务器,并使用秘钥进行了加密.
到此这篇关于Gin处理Session的实现的文章就介绍到这了,更多相关Gin处理Session内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
详解golang执行Linux shell命令完整场景下的使用方法
本文主要介绍了golang执行Linux shell命令完整场景下的使用方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2022-06-06


最新评论