72 lines
1.1 KiB
Go
72 lines
1.1 KiB
Go
![]() |
package filesystem
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"os"
|
||
|
"path/filepath"
|
||
|
)
|
||
|
|
||
|
func Open(path string) (*Storage, error) {
|
||
|
info, err := os.Stat(path)
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
if !info.IsDir() {
|
||
|
return nil, fmt.Errorf("provided path %s is not a directory", path)
|
||
|
}
|
||
|
|
||
|
abs, err := filepath.Abs(path)
|
||
|
if err != nil {
|
||
|
return nil, fmt.Errorf("could not tarnslate %s to absolute path", path)
|
||
|
}
|
||
|
|
||
|
return &Storage{prefix: abs}, nil
|
||
|
}
|
||
|
|
||
|
type Storage struct {
|
||
|
prefix string
|
||
|
}
|
||
|
|
||
|
func (s *Storage) Save(key string, data []byte) error {
|
||
|
path := s.toAbs(key)
|
||
|
|
||
|
if err := os.WriteFile(path, data, 0664); err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func (s *Storage) Load(key string) ([]byte, error) {
|
||
|
path := s.toAbs(key)
|
||
|
|
||
|
b, err := os.ReadFile(path)
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
return b, nil
|
||
|
}
|
||
|
|
||
|
func (s *Storage) Delete(key string) error {
|
||
|
path := s.toAbs(key)
|
||
|
|
||
|
err := os.Remove(path)
|
||
|
if err != nil && os.IsNotExist(err) {
|
||
|
return nil
|
||
|
} else if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func (s *Storage) Close() error {
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func (s *Storage) toAbs(path string) string {
|
||
|
return filepath.Join(s.prefix, path)
|
||
|
}
|