-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.go
113 lines (92 loc) · 2.26 KB
/
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package storage
import (
"context"
"errors"
"os"
"path/filepath"
)
type FileStorage struct {
dir string
}
func NewFileStorage(dir string) *FileStorage {
return &FileStorage{dir: dir}
}
func (s *FileStorage) Purge(ctx context.Context) error {
return os.RemoveAll(s.dir)
}
func (s *FileStorage) Get(ctx context.Context, key string) ([]byte, error) {
filePath := filepath.Join(s.dir, key)
data, err := os.ReadFile(filePath)
if err != nil {
return nil, err
}
return data, nil
}
func (s *FileStorage) GetMultiple(ctx context.Context, filePaths []string) ([]Object, error) {
var res []Object
for _, filePath := range filePaths {
data, err := os.ReadFile(filePath)
if err != nil {
return nil, err
}
res = append(res, Object{
Key: filePath,
Data: data,
})
}
return res, nil
}
func (s *FileStorage) Exists(ctx context.Context, key string) (bool, error) {
filePath := filepath.Join(s.dir, key)
_, err := os.Stat(filePath)
if err == nil {
return true, nil
}
if errors.Is(err, os.ErrNotExist) {
return false, nil
}
return false, err
}
func (s *FileStorage) List(ctx context.Context, prefix string) ([]Object, error) {
dirData, err := os.ReadDir(prefix)
if err != nil {
return nil, err
}
results := make([]Object, 0, len(dirData))
for _, dirEntry := range dirData {
results = append(results, Object{Key: dirEntry.Name()})
}
return results, nil
}
func (s *FileStorage) Delete(ctx context.Context, key string) error {
filePath := filepath.Join(s.dir, key)
return os.Remove(filePath)
}
func (s *FileStorage) Put(ctx context.Context, key string, data []byte) error {
if _, err := os.Stat(s.dir); errors.Is(err, os.ErrNotExist) {
if err := os.MkdirAll(s.dir, os.ModePerm); err != nil {
return err
}
}
keyDir := filepath.Join(s.dir, filepath.Dir(key))
if len(keyDir) > 0 {
if _, err := os.Stat(keyDir); errors.Is(err, os.ErrNotExist) {
if err := os.MkdirAll(keyDir, os.ModePerm); err != nil {
return err
}
}
}
filePath := filepath.Join(s.dir, key)
_, err := os.Stat(filePath)
if errors.Is(err, os.ErrNotExist) {
file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, os.ModePerm)
if err != nil {
return err
}
defer file.Close()
if _, err := file.Write(data); err != nil {
return err
}
}
return nil
}