This repository has been archived by the owner on Nov 2, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dir.go
91 lines (76 loc) · 1.71 KB
/
dir.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
package storage
import (
"go.uber.org/zap"
"io/ioutil"
"os"
"path"
"path/filepath"
)
type DirStorage struct {
logger *zap.SugaredLogger
rootDir string
}
func NewDirStorage(rootDir string) (*DirStorage, error) {
absPath, err := filepath.Abs(rootDir)
if err != nil {
return nil, err
}
return &DirStorage{
rootDir: absPath,
}, nil
}
func (s *DirStorage) GetObject(key string) (Object, error) {
var object Object
object.Path = key
fullPath := path.Join(s.rootDir, key)
content, err := ioutil.ReadFile(fullPath)
if err != nil {
return object, err
}
object.Data = content
info, err := os.Stat(fullPath)
if err != nil {
return object, err
}
object.LastModified = info.ModTime()
return object, err
}
func (s *DirStorage) PutObject(key string, data []byte) error {
fullPath := path.Join(s.rootDir, key)
folderPath := path.Dir(fullPath)
if _, err := os.Stat(folderPath); err != nil {
if os.IsNotExist(err) {
if err := os.MkdirAll(folderPath, 0777); err != nil {
return err
}
} else {
return err
}
}
if err := ioutil.WriteFile(fullPath, data, 0644); err != nil {
return err
}
return nil
}
func (s *DirStorage) DeleteObject(key string) error {
fullPath := path.Join(s.rootDir, key)
return os.Remove(fullPath)
}
func (s *DirStorage) ListObjects(prefix string) ([]Object, error) {
var objects []Object
files, err := ioutil.ReadDir(path.Join(s.rootDir, prefix))
if err != nil {
if os.IsNotExist(err) { // OK if the directory doesnt exist yet
err = nil
}
return objects, err
}
for _, f := range files {
if f.IsDir() {
continue
}
object := Object{Path: f.Name(), Data: []byte{}, LastModified: f.ModTime()}
objects = append(objects, object)
}
return objects, nil
}