forked from sajari/storage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.go
76 lines (62 loc) · 1.36 KB
/
cache.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
package storage
import (
"io"
"golang.org/x/net/context"
)
// Cache creates an FS implementation which caches files opened from src into cache.
func Cache(src, cache FS) FS {
return &cachedFS{
src: src,
cache: cache,
}
}
type cachedFS struct {
src, cache FS
}
// Open implements FS.
func (c *cachedFS) Open(ctx context.Context, path string) (*File, error) {
f, err := c.cache.Open(ctx, path)
if err == nil {
return f, nil
}
if !IsNotExist(err) {
return nil, err
}
sf, err1 := c.src.Open(ctx, path)
if err1 != nil {
return nil, err1
}
defer sf.Close()
wc, err := c.cache.Create(ctx, path)
if err != nil {
return nil, err
}
if _, err := io.Copy(wc, sf); err != nil {
wc.Close()
return nil, err
}
if err := wc.Close(); err != nil {
return nil, err
}
ff, err := c.cache.Open(ctx, path)
if err != nil {
return nil, err
}
return ff, nil
}
// Delete implements FS.
func (c *cachedFS) Delete(ctx context.Context, path string) error {
err := c.cache.Delete(ctx, path)
if err != nil && !IsNotExist(err) {
return err
}
return c.src.Delete(ctx, path)
}
// Create implements FS.
func (c *cachedFS) Create(ctx context.Context, path string) (io.WriteCloser, error) {
return c.src.Create(ctx, path)
}
// Walk implements FS.
func (c *cachedFS) Walk(ctx context.Context, path string, fn WalkFn) error {
return c.src.Walk(ctx, path, fn)
}