-
-
Notifications
You must be signed in to change notification settings - Fork 363
/
cache.go
96 lines (80 loc) · 2.15 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package app
import (
"context"
"sync"
"time"
"github.com/maxence-charriere/go-app/v9/pkg/cache"
)
// PreRenderCache is the interface that describes a cache that stores
// pre-rendered resources.
type PreRenderCache interface {
// Get returns the item at the given path.
Get(ctx context.Context, path string) (PreRenderedItem, bool)
// Set stored the item at the given path.
Set(ctx context.Context, i PreRenderedItem)
}
// PreRenderedItem represent an item that is stored in a PreRenderCache.
type PreRenderedItem struct {
// The request path.
Path string
// The response content type.
ContentType string
// The response content encoding.
ContentEncoding string
// The response body.
Body []byte
}
// Len return the body length.
func (r PreRenderedItem) Size() int {
return len(r.Body)
}
// NewPreRenderLRUCache creates an in memory LRU cache that stores items for the
// given duration. If provided, on eviction functions are called when item are
// evicted.
func NewPreRenderLRUCache(size int, itemTTL time.Duration, onEvict ...func(path string, i PreRenderedItem)) PreRenderCache {
return &preRenderLRUCache{
LRU: cache.LRU{
MaxSize: size,
ItemTTL: itemTTL,
OnEvict: func(path string, i cache.Item) {
item := i.(PreRenderedItem)
for _, fn := range onEvict {
fn(path, item)
}
},
},
}
}
type preRenderLRUCache struct {
cache.LRU
}
func (c *preRenderLRUCache) Get(ctx context.Context, path string) (PreRenderedItem, bool) {
i, ok := c.LRU.Get(ctx, path)
if !ok {
return PreRenderedItem{}, false
}
return i.(PreRenderedItem), true
}
func (c *preRenderLRUCache) Set(ctx context.Context, i PreRenderedItem) {
c.LRU.Set(ctx, i.Path, i)
}
type preRenderCache struct {
mu sync.RWMutex
items map[string]PreRenderedItem
}
func newPreRenderCache(size int) *preRenderCache {
return &preRenderCache{
items: make(map[string]PreRenderedItem, size),
}
}
func (c *preRenderCache) Set(ctx context.Context, i PreRenderedItem) {
c.mu.Lock()
c.items[i.Path] = i
c.mu.Unlock()
}
func (c *preRenderCache) Get(ctx context.Context, path string) (PreRenderedItem, bool) {
c.mu.Lock()
i, ok := c.items[path]
c.mu.Unlock()
return i, ok
}