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) {
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)
}