-
Notifications
You must be signed in to change notification settings - Fork 5
/
keystorage.go
110 lines (97 loc) · 2.08 KB
/
keystorage.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
package virgil
import (
"encoding/json"
"io/ioutil"
"os"
"path"
"path/filepath"
"gopkg.in/virgil.v4/errors"
)
type KeyStorage interface {
Store(key *StorageItem) error
Load(name string) (*StorageItem, error)
Exists(name string) bool
Delete(name string) error
}
type StorageItem struct {
Name string
Data []byte
Meta map[string]string
}
var (
ErrorKeyAlreadyExists = errors.New("Key already exists")
ErrorKeyNotFound = errors.New("Key not found")
)
type storageKeyJSON struct {
Data []byte
Meta map[string]string
}
type FileStorage struct {
RootDir string
}
func (s *FileStorage) Store(key *StorageItem) error {
dir, err := s.getRootDir()
if err != nil {
return err
}
if s.Exists(key.Name) {
return ErrorKeyAlreadyExists
}
data, err := json.Marshal(storageKeyJSON{
Data: key.Data,
Meta: key.Meta,
})
if err != nil {
return errors.Wrap(err, "FileStorage cannot marshal data")
}
ioutil.WriteFile(path.Join(dir, key.Name), data, 400)
return nil
}
func (s *FileStorage) Load(name string) (*StorageItem, error) {
dir, err := s.getRootDir()
if err != nil {
return nil, err
}
if !s.Exists(name) {
return nil, ErrorKeyNotFound
}
d, err := ioutil.ReadFile(path.Join(dir, name))
if err != nil {
return nil, errors.Wrap(err, "Cannot read file")
}
j := new(storageKeyJSON)
err = json.Unmarshal(d, j)
if err != nil {
return nil, errors.Wrap(err, "FileStorage cannot unmarshal data")
}
return &StorageItem{
Name: name,
Data: j.Data,
Meta: j.Meta,
}, nil
}
func (s *FileStorage) Exists(name string) bool {
dir, err := s.getRootDir()
if err != nil {
return false
}
_, err = os.Stat(path.Join(dir, name))
return !os.IsNotExist(err)
}
func (s *FileStorage) Delete(name string) error {
dir, err := s.getRootDir()
if err != nil {
return err
}
return os.Remove(path.Join(dir, name))
}
func (s *FileStorage) getRootDir() (string, error) {
if s.RootDir == "" {
var err error
s.RootDir, err = filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
return "", errors.Wrap(err, "FileStorage cannot get exutable path")
}
}
return s.RootDir, nil
}