passed/storage/ram.go

81 lines
1.2 KiB
Go

package storage
import (
"sync"
"time"
)
func NewRamStore() Store {
store := &ram{
passwords: make(map[string]ramEntry),
lock: sync.Mutex{},
}
return store
}
type ram struct {
passwords map[string]ramEntry
lock sync.Mutex
}
type ramEntry struct {
Password []byte
ExpiresAt time.Time
}
func (store *ram) Create(password []byte, expiresAt time.Time) (string, error) {
store.lock.Lock()
defer store.lock.Unlock()
for range 1000 {
id := generateId(24)
_, found := store.passwords[id]
if found {
continue
}
store.passwords[id] = ramEntry{
Password: password,
ExpiresAt: expiresAt,
}
return id, nil
}
return "", ErrFull
}
func (store *ram) Get(id string) ([]byte, error) {
store.lock.Lock()
defer store.lock.Unlock()
password, found := store.passwords[id]
if !found {
return nil, ErrNotFound
}
return password.Password, nil
}
func (store *ram) Delete(id string) error {
delete(store.passwords, id)
return nil
}
func (store *ram) ClearExpired() error {
store.lock.Lock()
defer store.lock.Unlock()
time := time.Now()
for id, password := range store.passwords {
if time.After(password.ExpiresAt) {
err := store.Delete(id)
if err != nil {
return err
}
}
}
return nil
}