package sessions import ( "strconv" "sync" "time" ) func NewMemStorage() Storage { storage := &memStorage{ sessions: make(map[string]Session), idCounter: 0, lock: sync.Mutex{}, } return storage } type memStorage struct { sessions map[string]Session idCounter uint64 lock sync.Mutex } func (s *memStorage) GetAllSessions() ([]Session, error) { s.lock.Lock() defer s.lock.Unlock() sessions := make([]Session, len(s.sessions)) i := 0 for _, session := range s.sessions { sessions[i] = session i += 1 } return sessions, nil } func (s *memStorage) GetActiveSessions() ([]Session, error) { s.lock.Lock() defer s.lock.Unlock() sessions := make([]Session, 0) for _, session := range s.sessions { if session.EndedAt.IsZero() { sessions = append(sessions, session) } } return sessions, nil } func (s *memStorage) GetPastSessions() ([]Session, error) { s.lock.Lock() defer s.lock.Unlock() sessions := make([]Session, 0) for _, session := range s.sessions { if !session.EndedAt.IsZero() { sessions = append(sessions, session) } } return sessions, nil } func (s *memStorage) StartSession(description string, createdAt time.Time) (Session, error) { s.lock.Lock() defer s.lock.Unlock() rawId := s.idCounter s.idCounter = rawId + 1 id := strconv.FormatUint(rawId, 10) session := Session{ Id: id, Description: description, CreatedAt: createdAt, EndedAt: time.Time{}, // This is the zero time } s.sessions[id] = session return session, nil } func (s *memStorage) EndSession(id string, endedAt time.Time) error { s.lock.Lock() defer s.lock.Unlock() session, found := s.sessions[id] if !found { return ErrUnknownSession } session.EndedAt = endedAt s.sessions[id] = session return nil } func (s *memStorage) DeleteSession(id string) error { s.lock.Lock() defer s.lock.Unlock() _, found := s.sessions[id] if !found { return ErrUnknownSession } delete(s.sessions, id) return nil } func (s *memStorage) String() string { return "mem" }