62 lines
1.2 KiB
Go
62 lines
1.2 KiB
Go
package storage
|
|
|
|
import (
|
|
"io"
|
|
"os"
|
|
"path"
|
|
)
|
|
|
|
var (
|
|
DiskStorageBasePath = []string{"data"}
|
|
)
|
|
|
|
type DiskStorage struct {
|
|
dir string
|
|
}
|
|
|
|
func NewDiskStorage(ids []string) (Storage, error) {
|
|
pth := path.Join(DiskStorageBasePath...)
|
|
idPth := path.Join(ids...)
|
|
dir := path.Join(pth, idPth)
|
|
s := &DiskStorage{dir: dir}
|
|
|
|
return s, nil
|
|
}
|
|
|
|
func (ds *DiskStorage) ensureDir() error {
|
|
pth := path.Dir(ds.dir + "/")
|
|
return os.MkdirAll(pth, 0777)
|
|
}
|
|
|
|
func (ds *DiskStorage) Get(key string) (io.Reader, error) {
|
|
f, err := os.Open(path.Join(ds.dir, key))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return f, nil
|
|
}
|
|
|
|
func (ds *DiskStorage) Put(key string, data []byte) error {
|
|
if err := ds.ensureDir(); err != nil {
|
|
return err
|
|
}
|
|
return os.WriteFile(path.Join(ds.dir, key), data, 0644)
|
|
}
|
|
|
|
func (ds *DiskStorage) Delete(key string) error {
|
|
// Implement disk storage delete logic here
|
|
return os.Remove(path.Join(ds.dir, key))
|
|
}
|
|
|
|
func (ds *DiskStorage) List(prefix string) ([]string, error) {
|
|
data, err := os.ReadDir(path.Join(ds.dir, prefix))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
res := make([]string, 0, len(data))
|
|
for _, file := range data {
|
|
res = append(res, file.Name())
|
|
}
|
|
return res, nil
|
|
}
|