Files
go-persist/pkg/storage/disk-storage.go
matst80 d65c9f6998
All checks were successful
Build and Publish / BuildAndDeploy (push) Successful in 34s
cleanup
2025-05-16 07:18:32 +02:00

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
}