This commit is contained in:
78
pkg/storage/disk-storage.go
Normal file
78
pkg/storage/disk-storage.go
Normal file
@@ -0,0 +1,78 @@
|
||||
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}
|
||||
err := s.ensureDir()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
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) {
|
||||
if err := ds.ensureDir(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
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
|
||||
}
|
||||
f, err := os.Open(path.Join(ds.dir, key))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = f.Write(data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return f.Close()
|
||||
}
|
||||
|
||||
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) {
|
||||
if err := ds.ensureDir(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user