Files
go-persist/pkg/storage/disk-storage.go
matst80 fa47d75541
All checks were successful
Build and Publish / BuildAndDeploy (push) Successful in 32s
apikey
2025-05-15 19:47:49 +02:00

70 lines
1.3 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
}
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) {
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
}