From 0b9c5cccf57fb58690604ba5443f3b6a5bc2f83f Mon Sep 17 00:00:00 2001 From: 1e99 Date: Sat, 9 Nov 2024 21:50:54 +0100 Subject: [PATCH] add getEntry to directory storage --- storage/dir.go | 54 ++++++++++++++++++++++---------------------------- 1 file changed, 24 insertions(+), 30 deletions(-) diff --git a/storage/dir.go b/storage/dir.go index 199bb4a..bf5d561 100644 --- a/storage/dir.go +++ b/storage/dir.go @@ -62,12 +62,7 @@ func (store *dir) Create(password []byte, expiresAt time.Time) (string, error) { } func (store *dir) Get(id string) ([]byte, error) { - path := store.getPath(id) - file, err := os.OpenFile( - path, - os.O_RDONLY, - 0, - ) + entry, err := store.getEntry(id) switch { case os.IsNotExist(err): return nil, ErrNotFound @@ -75,14 +70,6 @@ func (store *dir) Get(id string) ([]byte, error) { return nil, err } - defer file.Close() - - var entry dirEntry - err = gob.NewDecoder(file).Decode(&entry) - if err != nil { - return nil, err - } - return entry.Password, nil } @@ -106,27 +93,12 @@ func (store *dir) ClearExpired() error { for _, file := range entries { id := file.Name() - path := store.getPath(id) - file, err := os.OpenFile( - path, - os.O_RDONLY, - 0, - ) - if err != nil { - return err - } - - defer file.Close() - - var entry dirEntry - err = gob.NewDecoder(file).Decode(&entry) + entry, err := store.getEntry(id) if err != nil { return err } if now.After(entry.ExpiresAt) { - // Close file early as we need to delete it - file.Close() err = store.Delete(id) if err != nil { return err @@ -137,6 +109,28 @@ func (store *dir) ClearExpired() error { return nil } +func (store *dir) getEntry(id string) (dirEntry, error) { + path := store.getPath(id) + file, err := os.OpenFile( + path, + os.O_RDONLY, + 0, + ) + if err != nil { + return dirEntry{}, err + } + + defer file.Close() + + var entry dirEntry + err = gob.NewDecoder(file).Decode(&entry) + if err != nil { + return dirEntry{}, err + } + + return entry, nil +} + func (store *dir) getPath(id string) string { return path.Join(store.path, id) }