This repository has been archived by the owner on Oct 2, 2023. It is now read-only.
/
localstore.go
78 lines (62 loc) · 1.5 KB
/
localstore.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
package imagestore
import (
"io"
"os"
"path"
)
// A LocalImageStore stores images on the local disk.
type LocalImageStore struct {
storeRoot string
namePathMapper *NamePathMapper
}
func NewLocalImageStore(root string, mapper *NamePathMapper) *LocalImageStore {
return &LocalImageStore{
storeRoot: root,
namePathMapper: mapper,
}
}
func (this *LocalImageStore) Exists(obj *StoreObject) (bool, error) {
if _, err := os.Stat(this.toPath(obj)); os.IsNotExist(err) {
return false, err
}
return true, nil
}
func (this *LocalImageStore) Save(src string, obj *StoreObject) (*StoreObject, error) {
srcFd, err := os.Open(src)
if err != nil {
return nil, err
}
defer srcFd.Close()
// open output file
this.createParent(obj)
fo, err := os.Create(this.toPath(obj))
if err != nil {
return nil, err
}
defer fo.Close()
_, err = io.Copy(fo, srcFd)
if err != nil {
return nil, err
}
obj.Url = this.toPath(obj)
return obj, nil
}
func (this *LocalImageStore) Get(obj *StoreObject) (io.ReadCloser, error) {
reader, err := os.Open(this.toPath(obj))
if err != nil {
return nil, err
}
return reader, nil
}
func (this *LocalImageStore) String() string {
return "LocalStore"
}
func (this *LocalImageStore) createParent(obj *StoreObject) {
path := path.Dir(this.toPath(obj))
if _, err := os.Stat(path); os.IsNotExist(err) {
os.MkdirAll(path, 0777)
}
}
func (this *LocalImageStore) toPath(obj *StoreObject) string {
return this.storeRoot + "/" + this.namePathMapper.mapToPath(obj)
}