add getEntry to directory storage

This commit is contained in:
1e99 2024-11-09 21:50:54 +01:00
parent 3b74336efd
commit 0b9c5cccf5

View file

@ -62,12 +62,7 @@ func (store *dir) Create(password []byte, expiresAt time.Time) (string, error) {
} }
func (store *dir) Get(id string) ([]byte, error) { func (store *dir) Get(id string) ([]byte, error) {
path := store.getPath(id) entry, err := store.getEntry(id)
file, err := os.OpenFile(
path,
os.O_RDONLY,
0,
)
switch { switch {
case os.IsNotExist(err): case os.IsNotExist(err):
return nil, ErrNotFound return nil, ErrNotFound
@ -75,14 +70,6 @@ func (store *dir) Get(id string) ([]byte, error) {
return nil, err 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 return entry.Password, nil
} }
@ -106,27 +93,12 @@ func (store *dir) ClearExpired() error {
for _, file := range entries { for _, file := range entries {
id := file.Name() id := file.Name()
path := store.getPath(id) entry, err := store.getEntry(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)
if err != nil { if err != nil {
return err return err
} }
if now.After(entry.ExpiresAt) { if now.After(entry.ExpiresAt) {
// Close file early as we need to delete it
file.Close()
err = store.Delete(id) err = store.Delete(id)
if err != nil { if err != nil {
return err return err
@ -137,6 +109,28 @@ func (store *dir) ClearExpired() error {
return nil 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 { func (store *dir) getPath(id string) string {
return path.Join(store.path, id) return path.Join(store.path, id)
} }