2021-01-17 21:46:25 +08:00
|
|
|
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
|
2019-09-11 21:19:45 +08:00
|
|
|
//
|
|
|
|
|
// This Source Code Form is subject to the terms of the MIT License.
|
|
|
|
|
// If a copy of the MIT was not distributed with this file,
|
|
|
|
|
// You can obtain one at https://github.com/gogf/gf.
|
|
|
|
|
|
|
|
|
|
package gsession
|
|
|
|
|
|
|
|
|
|
import (
|
2021-06-26 16:23:54 +08:00
|
|
|
"context"
|
2019-09-11 21:19:45 +08:00
|
|
|
"time"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// Manager for sessions.
|
|
|
|
|
type Manager struct {
|
2021-04-02 18:00:50 +08:00
|
|
|
ttl time.Duration // TTL for sessions.
|
|
|
|
|
storage Storage // Storage interface for session storage.
|
2019-09-11 21:19:45 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// New creates and returns a new session manager.
|
|
|
|
|
func New(ttl time.Duration, storage ...Storage) *Manager {
|
|
|
|
|
m := &Manager{
|
2022-04-27 15:05:34 +08:00
|
|
|
ttl: ttl,
|
2019-09-11 21:19:45 +08:00
|
|
|
}
|
|
|
|
|
if len(storage) > 0 && storage[0] != nil {
|
|
|
|
|
m.storage = storage[0]
|
2019-10-29 16:45:42 +08:00
|
|
|
} else {
|
2022-04-27 15:05:34 +08:00
|
|
|
// It uses StorageFile in default.
|
|
|
|
|
m.storage = NewStorageFile(DefaultStorageFilePath, ttl)
|
2019-09-11 21:19:45 +08:00
|
|
|
}
|
|
|
|
|
return m
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// New creates or fetches the session for given session id.
|
2021-08-16 21:47:45 +08:00
|
|
|
// The parameter `sessionId` is optional, it creates a new one if not it's passed
|
2019-12-10 21:14:15 +08:00
|
|
|
// depending on Storage.New.
|
2021-06-26 16:23:54 +08:00
|
|
|
func (m *Manager) New(ctx context.Context, sessionId ...string) *Session {
|
2019-09-11 21:19:45 +08:00
|
|
|
var id string
|
|
|
|
|
if len(sessionId) > 0 && sessionId[0] != "" {
|
|
|
|
|
id = sessionId[0]
|
|
|
|
|
}
|
|
|
|
|
return &Session{
|
|
|
|
|
id: id,
|
2021-06-26 16:23:54 +08:00
|
|
|
ctx: ctx,
|
2019-09-11 21:19:45 +08:00
|
|
|
manager: m,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// SetStorage sets the session storage for manager.
|
|
|
|
|
func (m *Manager) SetStorage(storage Storage) {
|
|
|
|
|
m.storage = storage
|
|
|
|
|
}
|
|
|
|
|
|
2022-01-23 15:14:06 +08:00
|
|
|
// GetStorage returns the session storage of current manager.
|
|
|
|
|
func (m *Manager) GetStorage() Storage {
|
|
|
|
|
return m.storage
|
|
|
|
|
}
|
|
|
|
|
|
2019-09-15 12:17:44 +08:00
|
|
|
// SetTTL the TTL for the session manager.
|
|
|
|
|
func (m *Manager) SetTTL(ttl time.Duration) {
|
|
|
|
|
m.ttl = ttl
|
|
|
|
|
}
|
|
|
|
|
|
2022-04-27 15:05:34 +08:00
|
|
|
// GetTTL returns the TTL of the session manager.
|
|
|
|
|
func (m *Manager) GetTTL() time.Duration {
|
2019-09-11 21:19:45 +08:00
|
|
|
return m.ttl
|
|
|
|
|
}
|