78 lines
1.3 KiB
Go
78 lines
1.3 KiB
Go
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) HasSessions() (bool, error) {
|
|
s.lock.Lock()
|
|
defer s.lock.Unlock()
|
|
return len(s.sessions) > 0, nil
|
|
}
|
|
|
|
func (s *memStorage) GetSessions() ([]Session, error) {
|
|
s.lock.Lock()
|
|
defer s.lock.Unlock()
|
|
|
|
sessions := make([]Session, len(s.sessions))
|
|
id := 0
|
|
|
|
for _, session := range s.sessions {
|
|
sessions[id] = session
|
|
id += 1
|
|
}
|
|
|
|
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,
|
|
}
|
|
s.sessions[id] = session
|
|
|
|
return session, nil
|
|
}
|
|
|
|
func (s *memStorage) EndSession(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"
|
|
}
|