minipaste/store/memory.go

58 lines
885 B
Go
Raw Permalink Normal View History

2022-04-20 00:37:27 +00:00
package store
import (
"bytes"
"io"
"io/ioutil"
"github.com/google/uuid"
)
2022-04-20 20:51:06 +00:00
var _ Store = &MemoryStore{}
2022-04-20 00:37:27 +00:00
type MemoryStore struct {
data map[string][]byte
}
func NewMemoryStore() *MemoryStore {
return &MemoryStore{data: map[string][]byte{}}
}
func (s *MemoryStore) Add(r io.Reader) (string, error) {
id := uuid.Must(uuid.NewRandom()).String()
data, err := ioutil.ReadAll(r)
if err != nil {
return "", err
}
s.data[id] = data
return id, nil
}
func (s *MemoryStore) Delete(id string) error {
delete(s.data, id)
return nil
}
func (s *MemoryStore) Get(id string) (io.ReadCloser, error) {
data, ok := s.data[id]
if !ok {
return nil, ErrNoSuchItem
}
br := bytes.NewReader(data)
r := io.NopCloser(br)
return r, nil
}
2022-04-20 20:51:06 +00:00
func (s *MemoryStore) List() ([]string, error) {
var ids []string
for id := range s.data {
ids = append(ids, id)
}
return ids, nil
}