文章目录
Sessions介绍
因为http是无状态、短连接,如何保存客户端和服务器直接的会话状态呢?可以使用session。
session 是另一种记录客户状态的机制,不同的是 Cookie 保存在客户端浏览器中,而session保存在服务器上。
主要功能:
- 简单的API:将其用作设置签名(以及可选的加密)cookie的简便方法。
- 内置的后端可将session存储在cookie或文件系统中。
- Flash消息:一直持续读取的session值。
- 切换session持久性(又称“记住我”)和设置其他属性的便捷方法。
- 旋转身份验证和加密密钥的机制。
- 每个请求有多个session,即使使用不同的后端也是如此。
- 自定义session后端的接口和基础结构:可以使用通用API检索并批量保存来自不同商店的session。
工作流程:
当客户端浏览器第一次访问服务器并发送请求时,服务器端会创建一个session 对象,生成一个类似于 key-value 的键值对,然后将 value 保存到服务器 ,将 key(cookie)返回到浏览器(客户)端。浏览器下次访问时会携带 key(cookie),找到对应的 session(value)。
gin session中间件
gin 本身没有对session的支持,可以使用第三方中间件。
下载:
go get github.com/gin-contrib/sessions
导入:
import "github.com/gin-contrib/sessions"
该中间件提供了很多后端支持:
gin session中间件的基本使用
type Session
type Session interface {
// ID of the session, generated by stores. It should not be used for user data.
ID() string
// Get returns the session value associated to the given key.
Get(key interface{
}) interface{
}
// Set sets the session value associated to the given key.
Set(key interface{
}, val interface{
})
// Delete removes the session value associated to the given key.
Delete(key interface{
})
// Clear deletes all values in the session.
Clear()
// AddFlash adds a flash message to the session.
// A single variadic argument is accepted, and it is optional: it defines the flash key.
// If not defined "_flash" is used by default.
AddFlash(value interface{
}, vars ...string)
// Flashes returns a slice of flash messages from the session.
// A single variadic argument is accepted, and it is optional: it defines the flash key.