-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.go
59 lines (48 loc) · 1.38 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
package katsuragi
import (
"container/list"
"golang.org/x/net/html"
)
func (f *Fetcher) GetFromCache(url string) (*html.Node, bool, error) {
f.mu.RLock()
defer f.mu.RUnlock()
if elem, ok := f.cache[url]; ok {
f.lruList.MoveToFront(elem)
entry := elem.Value.(*cacheEntry)
if entry.isError {
return nil, true, entry.err
}
return entry.response, true, nil
}
return nil, false, nil
}
func (f *Fetcher) addToCache(url string, response *html.Node, err error) {
f.mu.Lock()
defer f.mu.Unlock()
isError := err != nil
if elem, ok := f.cache[url]; ok {
f.lruList.MoveToFront(elem)
entry := elem.Value.(*cacheEntry)
entry.response = response
entry.isError = isError
entry.err = err
return
}
// Evict the least recently used entry if the cache is full
if len(f.cache) >= f.props.CacheCap {
oldest := f.lruList.Back()
if oldest != nil {
delete(f.cache, oldest.Value.(*cacheEntry).url)
f.lruList.Remove(oldest)
}
}
entry := &cacheEntry{url: url, response: response, isError: isError, err: err}
elem := f.lruList.PushFront(entry)
f.cache[url] = elem
}
func (f *Fetcher) ClearCache() {
f.mu.Lock()
defer f.mu.Unlock()
f.cache = make(map[string]*list.Element)
f.lruList = list.New()
}