-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfilecache_118.go
72 lines (65 loc) · 1.52 KB
/
filecache_118.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
//go:build go1.18
package filecache
import (
"os"
"time"
)
func cacheFile(path string, maxSize int64, c []byte) (itm *cacheItem, err error) {
fi, err := os.Stat(path)
if err != nil {
return
} else if fi.Mode().IsDir() {
err = ItemIsDirectory
return
} else if fi.Size() > maxSize {
err = ItemTooLarge
return
}
if len(c) > 0 {
itm = &cacheItem{
name: path,
content: c,
Size: fi.Size(),
Modified: fi.ModTime(),
Lastaccess: time.Now(),
}
return
}
content, err := os.ReadFile(path)
if err != nil {
return
}
itm = &cacheItem{
name: path,
content: content,
Size: fi.Size(),
Modified: fi.ModTime(),
Lastaccess: time.Now(),
}
return
}
// ReadFile retrieves the file named by 'name'.
// If the file is not in the cache, load the file and cache the file in the
// background. If the file was not in the cache and the read was successful,
// the error ItemNotInCache is returned to indicate that the item was pulled
// from the filesystem and not the cache, unless the SquelchItemNotInCache
// global option is set; in that case, returns no error.
func (cache *FileCache) ReadFile(name string) (content []byte, err error) {
if cache.InCache(name) {
content, _ = cache.GetItem(name)
} else {
content, err = os.ReadFile(name)
if err == nil {
if !SquelchItemNotInCache {
err = ItemNotInCache
}
// async
go func(n string, c []byte) {
cache.Cache(n, c)
}(name, content)
} else {
// TODO whether try to cache file async ?
}
}
return
}