-
Notifications
You must be signed in to change notification settings - Fork 0
/
datastore_fs.go
51 lines (42 loc) · 1017 Bytes
/
datastore_fs.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package main
import (
"fmt"
"io"
"os"
"path/filepath"
)
type DataStoreFileSystem struct {
rootDir string
}
func NewFileSystemDataStore(root string) *DataStoreFileSystem {
return &DataStoreFileSystem{
rootDir: root,
}
}
func (s *DataStoreFileSystem) Get(key string) (io.ReadCloser, error) {
fullPath := filepath.Join(s.rootDir, key)
f, err := os.Open(fullPath)
if err != nil {
return nil, fmt.Errorf("error opening file %q:%w", fullPath, err)
}
return f, nil
}
func (s *DataStoreFileSystem) Set(key string, val io.ReadCloser) error {
fullPath := filepath.Join(s.rootDir, key)
dir, _ := filepath.Split(fullPath)
err := os.MkdirAll(dir, 0700)
if err != nil {
return fmt.Errorf("error making parent directory %s: %w", dir, err)
}
var file *os.File
file, err = os.Create(fullPath)
if err != nil {
return fmt.Errorf("error uploading: %w", err)
}
defer file.Close()
_, err = io.Copy(file, val)
if err != nil {
return fmt.Errorf("error uploading: %w", err)
}
return val.Close()
}