gsession_manager.go 1.7 KB

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