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