allow storage to close

This commit is contained in:
1e99 2024-10-30 00:21:25 +01:00
parent 7d21bde292
commit dfa37fc7fa
3 changed files with 28 additions and 18 deletions

View file

@ -20,6 +20,8 @@ func run() error {
return err
}
defer storage.Close()
mux := http.NewServeMux()
mux.Handle("GET /", routes.ServeFiles(embedFS, "static"))
mux.Handle("POST /api/password", routes.CreatePassword(storage, 12*1024, base64.StdEncoding))

View file

@ -10,23 +10,17 @@ func NewRamStore() Store {
store := &ram{
passwords: make(map[string]entry),
lock: sync.Mutex{},
close: make(chan bool),
}
go func() {
ticker := time.Tick(25 * time.Second)
for {
store.clearExpired()
<-ticker
}
}()
go store.clearExpired()
return store
}
type ram struct {
passwords map[string]entry
lock sync.Mutex
close chan bool
}
func (store *ram) CreatePassword(password []byte, expiresAt time.Time) (string, error) {
@ -64,7 +58,20 @@ func (store *ram) GetPassword(id string) ([]byte, error) {
return password.password, nil
}
func (store *ram) Close() error {
store.close <- true
return nil
}
func (store *ram) clearExpired() error {
ticker := time.NewTicker(20 * time.Second)
defer ticker.Stop()
for {
select {
case <-store.close:
return nil
case <-ticker.C:
store.lock.Lock()
defer store.lock.Unlock()
time := time.Now()
@ -74,8 +81,8 @@ func (store *ram) clearExpired() error {
delete(store.passwords, id)
}
}
return nil
}
}
}
func (store *ram) generateId(length int) string {

View file

@ -21,6 +21,7 @@ type entry struct {
type Store interface {
CreatePassword(password []byte, expiresAt time.Time) (string, error)
GetPassword(id string) ([]byte, error)
Close() error
}
func NewStore() (Store, error) {