gpaste/files/filestore_memory.go

97 lines
1.4 KiB
Go
Raw Normal View History

2022-01-20 02:40:32 +00:00
package files
2022-01-15 18:07:33 +00:00
import (
"bytes"
"fmt"
"io"
"sync"
"time"
)
type fileData struct {
ID string
Body bytes.Buffer
MaxViews uint
ExpiresOn time.Time
2022-01-24 14:52:15 +00:00
FileSize int64
2022-01-15 18:07:33 +00:00
}
type MemoryFileStore struct {
lock sync.RWMutex
data map[string]*fileData
}
func NewMemoryFileStore() *MemoryFileStore {
return &MemoryFileStore{
data: make(map[string]*fileData),
}
}
func (s *MemoryFileStore) Store(f *File) error {
data := &fileData{
ID: f.ID,
MaxViews: f.MaxViews,
ExpiresOn: f.ExpiresOn,
}
2022-01-24 14:52:15 +00:00
n, err := io.Copy(&data.Body, f.Body)
2022-01-15 18:07:33 +00:00
_ = f.Body.Close()
2022-01-24 14:52:15 +00:00
data.FileSize = n
2022-01-15 18:07:33 +00:00
s.lock.Lock()
defer s.lock.Unlock()
s.data[f.ID] = data
2022-01-24 19:25:52 +00:00
2022-01-15 18:07:33 +00:00
return err
}
func (s *MemoryFileStore) Get(id string) (*File, error) {
s.lock.RLock()
defer s.lock.RUnlock()
fd, ok := s.data[id]
if !ok {
return nil, fmt.Errorf("no such item")
}
2022-01-24 19:25:52 +00:00
2022-01-24 22:18:13 +00:00
body := new(bytes.Buffer)
if _, err := body.Write(fd.Body.Bytes()); err != nil {
return nil, err
}
2022-01-15 18:07:33 +00:00
f := &File{
ID: fd.ID,
MaxViews: fd.MaxViews,
ExpiresOn: fd.ExpiresOn,
2022-01-24 22:18:13 +00:00
Body: io.NopCloser(body),
2022-01-24 15:38:17 +00:00
FileSize: fd.FileSize,
2022-01-15 18:07:33 +00:00
}
return f, nil
}
func (s *MemoryFileStore) Delete(id string) error {
s.lock.Lock()
2022-01-15 20:31:32 +00:00
defer s.lock.Unlock()
2022-01-24 19:25:52 +00:00
2022-01-15 18:07:33 +00:00
delete(s.data, id)
2022-01-24 19:25:52 +00:00
2022-01-15 18:07:33 +00:00
return nil
}
func (s *MemoryFileStore) List() ([]string, error) {
2022-01-24 19:25:52 +00:00
ids := make([]string, 0, len(s.data))
2022-01-15 18:07:33 +00:00
s.lock.RLock()
defer s.lock.RUnlock()
2022-01-24 19:25:52 +00:00
2022-01-15 18:07:33 +00:00
for id := range s.data {
ids = append(ids, id)
}
2022-01-24 19:25:52 +00:00
2022-01-15 18:07:33 +00:00
return ids, nil
}