Moonshark/core/sessions/Session.go
2025-03-29 15:58:23 -05:00

72 lines
1.4 KiB
Go

package sessions
import (
"sync"
"time"
)
// Session stores data for a single user session
type Session struct {
ID string
Data map[string]any
CreatedAt time.Time
UpdatedAt time.Time
mu sync.RWMutex // Protect concurrent access to Data
}
// NewSession creates a new session with the given ID
func NewSession(id string) *Session {
now := time.Now()
return &Session{
ID: id,
Data: make(map[string]any),
CreatedAt: now,
UpdatedAt: now,
}
}
// Get retrieves a value from the session
func (s *Session) Get(key string) any {
s.mu.RLock()
defer s.mu.RUnlock()
return s.Data[key]
}
// Set stores a value in the session
func (s *Session) Set(key string, value any) {
s.mu.Lock()
defer s.mu.Unlock()
s.Data[key] = value
s.UpdatedAt = time.Now()
}
// Delete removes a value from the session
func (s *Session) Delete(key string) {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.Data, key)
s.UpdatedAt = time.Now()
}
// Clear removes all data from the session
func (s *Session) Clear() {
s.mu.Lock()
defer s.mu.Unlock()
s.Data = make(map[string]any)
s.UpdatedAt = time.Now()
}
// GetAll returns a copy of all session data
func (s *Session) GetAll() map[string]any {
s.mu.RLock()
defer s.mu.RUnlock()
// Create a copy to avoid concurrent map access issues
copy := make(map[string]any, len(s.Data))
for k, v := range s.Data {
copy[k] = v
}
return copy
}