gsession_manager.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. "github.com/gogf/gf/container/gmap"
  10. "time"
  11. "github.com/gogf/gf/os/gcache"
  12. )
  13. // Manager for sessions.
  14. type Manager struct {
  15. ttl time.Duration // TTL for sessions.
  16. storage Storage // Storage interface for session storage.
  17. // sessionData is the memory data cache for session TTL,
  18. // which is available only if the Storage does not stores any session data in synchronizing.
  19. // Please refer to the implements of StorageFile, StorageMemory and StorageRedis.
  20. sessionData *gcache.Cache
  21. }
  22. // New creates and returns a new session manager.
  23. func New(ttl time.Duration, storage ...Storage) *Manager {
  24. m := &Manager{
  25. ttl: ttl,
  26. sessionData: gcache.New(),
  27. }
  28. if len(storage) > 0 && storage[0] != nil {
  29. m.storage = storage[0]
  30. } else {
  31. m.storage = NewStorageFile()
  32. }
  33. return m
  34. }
  35. // New creates or fetches the session for given session id.
  36. // The parameter `sessionId` is optional, it creates a new one if not it's passed
  37. // depending on Storage.New.
  38. func (m *Manager) New(ctx context.Context, sessionId ...string) *Session {
  39. var id string
  40. if len(sessionId) > 0 && sessionId[0] != "" {
  41. id = sessionId[0]
  42. }
  43. return &Session{
  44. id: id,
  45. ctx: ctx,
  46. manager: m,
  47. }
  48. }
  49. // SetStorage sets the session storage for manager.
  50. func (m *Manager) SetStorage(storage Storage) {
  51. m.storage = storage
  52. }
  53. // SetTTL the TTL for the session manager.
  54. func (m *Manager) SetTTL(ttl time.Duration) {
  55. m.ttl = ttl
  56. }
  57. // TTL returns the TTL of the session manager.
  58. func (m *Manager) TTL() time.Duration {
  59. return m.ttl
  60. }
  61. // UpdateSessionTTL updates the ttl for given session.
  62. func (m *Manager) UpdateSessionTTL(sessionId string, data *gmap.StrAnyMap) {
  63. m.sessionData.Set(sessionId, data, m.ttl)
  64. }