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 filecache
import (
"encoding/hex"
"errors"
"io"
"os"
"path"
"path/filepath"
)
// New returns a new Cache implemented by fileCache.
func New(dir string) Cache {
return newFileCache(dir)
}
func newFileCache(dir string) *fileCache {
return &fileCache{dirPath: dir}
}
// fileCache persists compiled functions into dirPath.
//
// Note: this can be expanded to do binary signing/verification, set TTL on each entry, etc.
type fileCache struct {
dirPath string
}
func (fc *fileCache) path(key Key) string {
return path.Join(fc.dirPath, hex.EncodeToString(key[:]))
}
func (fc *fileCache) Get(key Key) (content io.ReadCloser, ok bool, err error) {
f, err := os.Open(fc.path(key))
if errors.Is(err, os.ErrNotExist) {
return nil, false, nil
} else if err != nil {
return nil, false, err
} else {
return f, true, nil
}
}
func (fc *fileCache) Add(key Key, content io.Reader) (err error) {
path := fc.path(key)
dirPath, fileName := filepath.Split(path)
file, err := os.CreateTemp(dirPath, fileName+".*.tmp")
if err != nil {
return
}
defer func() {
file.Close()
if err != nil {
_ = os.Remove(file.Name())
}
}()
if _, err = io.Copy(file, content); err != nil {
return
}
if err = file.Sync(); err != nil {
return
}
if err = file.Close(); err != nil {
return
}
err = os.Rename(file.Name(), path)
return
}
func (fc *fileCache) Delete(key Key) (err error) {
err = os.Remove(fc.path(key))
if errors.Is(err, os.ErrNotExist) {
err = nil
}
return
}
|