Session

原文: https://docs.gofiber.io/api/middleware/session

Session

Session middleware for Fiber.

​ Fiber 的会话中间件。

NOTE 注意

This middleware uses our Storage package to support various databases through a single interface. The default configuration for this middleware saves data to memory, see the examples below for other databases.

​ 此中间件使用我们的存储包通过单个接口支持各种数据库。此中间件的默认配置将数据保存到内存中,请参阅以下示例以了解其他数据库。

Signatures 签名

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
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
func (s *Session) SetExpiry(exp time.Duration)

CAUTION 注意

Storing interface{} values are limited to built-ins Go types.

​ 存储 interface{} 值仅限于内建的 Go 数据类型。

Examples 示例

Import the middleware package that is part of the Fiber web framework

​ 导入 Fiber Web 框架的一部分中间件包

1
2
3
4
import (
  "github.com/gofiber/fiber/v2"
  "github.com/gofiber/fiber/v2/middleware/session"
)

After you initiate your Fiber app, you can use the following possibilities:

​ 在启动 Fiber 应用后,您可以使用以下可能性:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// 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))
})

Config 配置

Property 属性Type 输入Description 说明Default 默认
Expiration 过期time.DurationAllowed session duration. 允许的会话持续时间。24 * time.Hour
Storagefiber.StorageStorage interface to store the session data. 存储会话数据的存储接口。memory.New()
KeyLookupstringKeyLookup is a string in the form of “<source>:<name>” that is used to extract session id from the request. KeyLookup 是一个 " <source>:<name> " 形式的字符串,用于从请求中提取会话 ID。"cookie:session_id"
CookieDomainstringDomain of the cookie. Cookie 的域。""
CookiePathstringPath of the cookie. Cookie 的路径。""
CookieSecureboolIndicates if cookie is secure. 指示 Cookie 是否安全。false
CookieHTTPOnly 指明是否安全。boolIndicates if cookie is HTTP only. 指示 Cookie 是否仅限 HTTP。false
CookieSameSite Site 的值。stringValue of SameSite cookie. “Lax”"Lax"
CookieSessionOnly 决定令牌是否仅持续一次浏览器的会话。如果设置为真,则忽略过期时间。boolDecides whether cookie should last for only the browser session. Ignores Expiration if set to true. 决定 Cookie 是否仅持续浏览器会话。如果设置为 true,则忽略过期时间。false
KeyGeneratorfunc() stringKeyGenerator generates the session key. KeyGenerator 生成会话键。utils.UUIDv4
CookieName (Deprecated) CookieName(已弃用)stringDeprecated: Please use KeyLookup. The session name. 已弃用:请使用 KeyLookup。会话名称。""

Default Config 默认配置

1
2
3
4
5
6
7
var ConfigDefault = Config{
    Expiration:   24 * time.Hour,
    KeyLookup:    "cookie:session_id",
    KeyGenerator: utils.UUIDv4,
    source:       "cookie",
    sessionName:  "session_id",
}

Constants 常量

1
2
3
4
5
const (
    SourceCookie   Source = "cookie"
    SourceHeader   Source = "header"
    SourceURLQuery Source = "query"
)

Custom Storage/Database 自定义存储/数据库

You can use any storage from our storage package.

​ 您可以使用存储包中的任何存储。

1
2
3
4
storage := sqlite3.New() // From github.com/gofiber/storage/sqlite3
store := session.New(session.Config{
    Storage: storage,
})

To use the store, see the Examples.

​ 要使用存储,请参阅示例。

最后修改 February 5, 2024: 更新 (f57b279)