gsession_manager.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package gsession
  7. import (
  8. "context"
  9. "time"
  10. )
  11. // Manager for sessions.
  12. type Manager struct {
  13. ttl time.Duration // TTL for sessions.
  14. storage Storage // Storage interface for session storage.
  15. }
  16. // New creates and returns a new session manager.
  17. func New(ttl time.Duration, storage ...Storage) *Manager {
  18. m := &Manager{
  19. ttl: ttl,
  20. }
  21. if len(storage) > 0 && storage[0] != nil {
  22. m.storage = storage[0]
  23. } else {
  24. // It uses StorageFile in default.
  25. m.storage = NewStorageFile(DefaultStorageFilePath, ttl)
  26. }
  27. return m
  28. }
  29. // New creates or fetches the session for given session id.
  30. // The parameter `sessionId` is optional, it creates a new one if not it's passed
  31. // depending on Storage.New.
  32. func (m *Manager) New(ctx context.Context, sessionId ...string) *Session {
  33. var id string
  34. if len(sessionId) > 0 && sessionId[0] != "" {
  35. id = sessionId[0]
  36. }
  37. return &Session{
  38. id: id,
  39. ctx: ctx,
  40. manager: m,
  41. }
  42. }
  43. // SetStorage sets the session storage for manager.
  44. func (m *Manager) SetStorage(storage Storage) {
  45. m.storage = storage
  46. }
  47. // GetStorage returns the session storage of current manager.
  48. func (m *Manager) GetStorage() Storage {
  49. return m.storage
  50. }
  51. // SetTTL the TTL for the session manager.
  52. func (m *Manager) SetTTL(ttl time.Duration) {
  53. m.ttl = ttl
  54. }
  55. // GetTTL returns the TTL of the session manager.
  56. func (m *Manager) GetTTL() time.Duration {
  57. return m.ttl
  58. }