-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathitem.go
85 lines (65 loc) · 1.32 KB
/
item.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
package filecache
import (
"io/fs"
"os"
"path/filepath"
"sync"
"time"
)
type item struct {
content []byte
mu sync.Mutex
AccesedAt time.Time
ModifiedAt time.Time
}
func (i *item) Duration() time.Duration {
i.mu.Lock()
defer i.mu.Unlock()
return time.Since(i.ModifiedAt)
}
func (i *item) Access() []byte {
i.mu.Lock()
defer i.mu.Unlock()
i.AccesedAt = time.Now()
return i.content
}
func getCacheItem(path string, maxSize int64) (*item, error) {
info, err := os.Stat(path)
if err != nil {
return nil, ErrNotFound
} else if info.IsDir() {
return nil, ErrIsDirectory
} else if info.Size() > maxSize {
return nil, ErrTooLarge
}
content, err := os.ReadFile(path)
if err != nil {
return nil, err
}
item := &item{
content: content,
ModifiedAt: info.ModTime(),
}
return item, nil
}
func setCacheItem(path string, content []byte, maxSize int64) (*item, error) {
if int64(len(content)) > maxSize {
return nil, ErrTooLarge
}
item := &item{
content: content,
}
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, fs.ModePerm); err != nil {
return nil, ErrInvalidKey
}
err := os.WriteFile(path, content, os.FileMode(0o644))
if err != nil {
return nil, err
}
item.ModifiedAt = time.Now()
return item, nil
}
func deleteCacheItem(path string) error {
return os.Remove(path)
}