会话
适用于 Fiber 的会话中间件。
注意
此中间件使用我们的 存储 包,通过单一接口支持各种数据库。此中间件的默认配置将数据保存到内存中,有关其他数据库,请参阅下面的示例。
签名
func New(config ...Config) *Store
func (s *Store) RegisterType(i interface{})
func (s *Store) Get(c *fiber.Ctx) (*Session, error)
func (s *Store) Delete(id string) error
func (s *Store) Reset() error
func (s *Session) Get(key string) interface{}
func (s *Session) Set(key string, val interface{})
func (s *Session) Delete(key string)
func (s *Session) Destroy() error
func (s *Session) Reset() error
func (s *Session) Regenerate() error
func (s *Session) Save() error
func (s *Session) Fresh() bool
func (s *Session) ID() string
func (s *Session) Keys() []string
注意
存储 interface{}
值仅限于 Go 内建类型。
示例
导入作为 Fiber Web 框架一部分的中间件包
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/session"
)
初始化 Fiber 应用后,您可以使用以下可能性
// Initialize default config
// This stores all of your app's sessions
store := session.New()
app.Get("/", func(c *fiber.Ctx) error {
// Get session from storage
sess, err := store.Get(c)
if err != nil {
panic(err)
}
// Get value
name := sess.Get("name")
// Set key/value
sess.Set("name", "john")
// Get all Keys
keys := sess.Keys()
// Delete key
sess.Delete("name")
// Destroy session
if err := sess.Destroy(); err != nil {
panic(err)
}
// Sets a specific expiration for this session
sess.SetExpiry(time.Second * 2)
// Save session
if err := sess.Save(); err != nil {
panic(err)
}
return c.SendString(fmt.Sprintf("Welcome %v", name))
})
配置
属性 | 类型 | 描述 | 默认值 |
---|---|---|---|
过期时间 | time.Duration | 允许的会话持续时间。 | 24 * time.Hour |
存储 | fiber.Storage | 用于存储会话数据的存储接口。 | memory.New() |
KeyLookup | string | KeyLookup 是一个字符串,格式为 "<source>:<name> ",用于从请求中提取会话 ID。 | "cookie:session_id" |
Cookie 域 | string | Cookie 的域。 | "" |
Cookie 路径 | string | Cookie 的路径。 | "" |
Cookie 安全 | bool | 指示 cookie 是否安全。 | false |
Cookie 仅限 HTTP | bool | 指示 cookie 是否仅限 HTTP。 | false |
Cookie SameSite | string | SameSite cookie 的值。 | "Lax" |
Cookie 仅会话 | bool | 决定 cookie 是否仅在浏览器会话期间有效。如果设置为 true,将忽略 Expiration。 | false |
KeyGenerator | func() string | KeyGenerator 生成会话密钥。 | utils.UUIDv4 |
CookieName (已弃用) | string | 已弃用:请使用 KeyLookup。会话名称。 | "" |
默认配置
var ConfigDefault = Config{
Expiration: 24 * time.Hour,
KeyLookup: "cookie:session_id",
KeyGenerator: utils.UUIDv4,
source: "cookie",
sessionName: "session_id",
}
常量
const (
SourceCookie Source = "cookie"
SourceHeader Source = "header"
SourceURLQuery Source = "query"
)
自定义存储/数据库
您可以使用我们的 存储 包中的任何存储。
storage := sqlite3.New() // From github.com/gofiber/storage/sqlite3
store := session.New(session.Config{
Storage: storage,
})
要使用此存储,请参阅示例。