-
Notifications
You must be signed in to change notification settings - Fork 7
/
file.go
55 lines (45 loc) · 970 Bytes
/
file.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
52
53
54
55
package storage
import (
"context"
"errors"
"io/ioutil"
"os"
"path/filepath"
)
type FileStorage struct {
Storage
root string
}
func NewFileStorage(rootDir string) (*FileStorage, error) {
path, err := filepath.Abs(rootDir)
if err != nil {
return nil, err
}
f, err := os.Open(path)
if err != nil {
return nil, err
}
s, err := f.Stat()
if err != nil {
return nil, err
}
if !s.Mode().IsDir() {
return nil, errors.New("root dir for file storage must be a dir")
}
return &FileStorage{root: rootDir}, nil
}
func (s *FileStorage) Store(ctx context.Context, data []byte, filename string) (*StorageObject, error) {
url := s.root + "/" + filename
err := ioutil.WriteFile(url, data, os.ModePerm)
if err != nil {
return nil, err
}
return &StorageObject{
Filename: filename,
URL: url,
}, nil
}
func (s *FileStorage) Delete(ctx context.Context, filename string) error {
p := filepath.Join(s.root, filename)
return os.Remove(p)
}