Files
mtusi2026lab5/app/internal/session/memory.go
T

50 lines
987 B
Go

package session
import (
"context"
"sync"
"time"
)
var _ Store = (*Memory)(nil)
type Memory struct {
mu sync.Mutex
sessions map[string]Session
now func() time.Time
}
func NewMemory() *Memory {
return &Memory{sessions: make(map[string]Session), now: time.Now}
}
func (m *Memory) Save(_ context.Context, tokenHash []byte, s Session) error {
m.mu.Lock()
defer m.mu.Unlock()
m.sessions[string(tokenHash)] = s
return nil
}
func (m *Memory) Get(_ context.Context, tokenHash []byte) (Session, error) {
m.mu.Lock()
defer m.mu.Unlock()
s, ok := m.sessions[string(tokenHash)]
if !ok {
return Session{}, ErrNotFound
}
if !m.now().Before(s.ExpiresAt) {
delete(m.sessions, string(tokenHash))
return Session{}, ErrNotFound
}
return s, nil
}
func (m *Memory) Delete(_ context.Context, tokenHash []byte) error {
m.mu.Lock()
defer m.mu.Unlock()
delete(m.sessions, string(tokenHash))
return nil
}
func (m *Memory) Ping(context.Context) error { return nil }