-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
89 lines (73 loc) · 1.94 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
package blobstore
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path"
"reflect"
"sync"
)
// File store saves each key value as a seperate file in the folder
// that's specified in the Path
// This is meant to be used only for local testing and usage.
type FileStore struct {
Name string
Path string
mutex sync.Mutex
}
func NewFile(name string, config BlobStoreConfig) (*FileStore, error) {
Path := path.Join(config.GetString("filesPath"), name)
os.MkdirAll(Path, os.ModePerm)
return &FileStore{
Name: name,
Path: Path,
}, nil
}
func (file *FileStore) Store(key string, object interface{}) error {
file.mutex.Lock()
defer file.mutex.Unlock()
filePath := path.Join(file.Path, key)
if err := WriteObjectToFile(filePath, object); err != nil {
return fmt.Errorf("Unable to store file: %s", err.Error())
}
return nil
}
func (file *FileStore) Load(key string, object interface{}) error {
file.mutex.Lock()
defer file.mutex.Unlock()
if object == nil || reflect.ValueOf(object).IsNil() {
return errors.New("Unable to load file to nil struct")
}
filePath := path.Join(file.Path, key)
if err := LoadFileToObject(filePath, object); err != nil {
return err
}
return nil
}
func (file *FileStore) LoadAll(f func() interface{}) (interface{}, error) {
file.mutex.Lock()
defer file.mutex.Unlock()
items := []interface{}{}
files, filesErr := ioutil.ReadDir(file.Path)
if filesErr != nil {
return nil, fmt.Errorf("Unable to read directory %s: %s", file.Path, filesErr.Error())
}
for _, fileInfo := range files {
if fileInfo.IsDir() {
continue
}
v := f()
filePath := path.Join(file.Path, fileInfo.Name())
if err := LoadFileToObject(filePath, v); err != nil {
return nil, fmt.Errorf("Unable to load file %s: %s", filePath, err.Error())
}
items = append(items, v)
}
return items, nil
}
func (file *FileStore) Delete(key string) error {
file.mutex.Lock()
defer file.mutex.Unlock()
return os.Remove(path.Join(file.Path, key))
}