-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmemory.go
More file actions
40 lines (34 loc) · 857 Bytes
/
memory.go
File metadata and controls
40 lines (34 loc) · 857 Bytes
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
package httpcache
import (
"fmt"
"net/url"
"sync"
"time"
"github.com/golang/groupcache/lru"
)
// A memoryCache implements a cache with files saved in Path.
type memoryCache struct {
sync.Mutex
Cache *lru.Cache
}
// newMemoryCache creates a new memory cache using groupcache's lru.
func newMemoryCache(maxItems int) *memoryCache {
return &memoryCache{Cache: lru.New(maxItems)}
}
// Get gets data saved for an URL if present in cache.
func (m *memoryCache) Get(u *url.URL) (*entry, error) {
m.Lock()
defer m.Unlock()
data, ok := m.Cache.Get(u.String())
if !ok {
return nil, fmt.Errorf("httpcache: %s not in cache", u)
}
return data.(*entry), nil
}
// Put puts data of an URL in cache.
func (m *memoryCache) Put(u *url.URL, data []byte) error {
m.Lock()
defer m.Unlock()
m.Cache.Add(u.String(), &entry{data, time.Now()})
return nil
}