forked from moul/blog-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcached_http_download.go
More file actions
82 lines (71 loc) · 1.63 KB
/
cached_http_download.go
File metadata and controls
82 lines (71 loc) · 1.63 KB
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
package main
import (
"sync"
"time"
"github.com/kjk/common/httputil"
)
// TODO: remember and use e-tag for re-downloads
// TODO: add disk cache
type httpDownloadCacheEntry struct {
url string
data []byte
downloadedOn time.Time
}
// HTTPDownloadCache is a cache for http downloads
type HTTPDownloadCache struct {
expirationTime time.Duration
m map[string]*httpDownloadCacheEntry
mu sync.Mutex
}
// NewHTTPDownloadCache creates HTTPDownloadCache
func NewHTTPDownloadCache() *HTTPDownloadCache {
cache := &HTTPDownloadCache{
expirationTime: time.Hour * 24,
m: map[string]*httpDownloadCacheEntry{},
}
// run a task to remove expired
go func() {
for {
// sleep for a bit longer than exipration time
time.Sleep(cache.expirationTime + time.Minute*4)
cache.removeAllExpired()
}
}()
return cache
}
func (c *HTTPDownloadCache) removeAllExpired() {
c.mu.Lock()
defer c.mu.Unlock()
var toRemove []string
for k, e := range c.m {
if time.Since(e.downloadedOn) > time.Hour*24 {
toRemove = append(toRemove, k)
}
}
for _, k := range toRemove {
delete(c.m, k)
}
}
// Download downloads url
func (c *HTTPDownloadCache) Download(uri string) ([]byte, bool, error) {
c.mu.Lock()
e := c.m[uri]
c.mu.Unlock()
// re-download after 24 hours
if e != nil && time.Since(e.downloadedOn) < c.expirationTime {
return e.data, true, nil
}
d, err := httputil.Get(uri)
if err != nil {
return nil, false, err
}
e = &httpDownloadCacheEntry{
url: uri,
data: d,
downloadedOn: time.Now(),
}
c.mu.Lock()
defer c.mu.Unlock()
c.m[uri] = e
return d, false, nil
}