-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathcache.go
63 lines (52 loc) · 1.27 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
package main
import (
"net/url"
"time"
"github.com/patrickmn/go-cache"
)
var endpointCache *cache.Cache
func init() {
// default expiration time of 1 minute
// and purges expired items every minutes
endpointCache = cache.New(1*time.Minute, 1*time.Minute)
}
type EndpointStatus = int32
const (
NotCached EndpointStatus = iota
TemporaryUnavailable
Refused
)
func getHost(url *url.URL) string {
return url.Scheme + "://" + url.Host
}
func getEndpointStatus(url *url.URL) EndpointStatus {
status, found := endpointCache.Get("host:" + getHost(url))
if found {
if s, ok := status.(EndpointStatus); ok {
return s
}
}
status, found = endpointCache.Get(url.String())
if found {
if s, ok := status.(EndpointStatus); ok {
return s
}
}
return NotCached
}
func cacheStatus(id string, status EndpointStatus) {
dur := cache.DefaultExpiration
// Cache for 10 minutes if the endpoint is refused
if status == Refused {
dur = 10 * time.Minute
}
endpointCache.Set(id, status, dur)
}
func setEndpointStatus(url *url.URL, status EndpointStatus) {
cacheStatus(url.String(), status)
}
func setHostStatus(url *url.URL, status EndpointStatus) {
// The suffix "host:" avoid considering a cached endpoint
// as a host endpoint
cacheStatus("host:"+getHost(url), status)
}