-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcacheresolver.go
53 lines (45 loc) · 1.13 KB
/
cacheresolver.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
package main
import (
"errors"
"time"
"github.com/codebear4/ttlcache"
)
// CacheResolver In-memory based host resolver
type CacheResolver struct {
store *ttlcache.Cache
}
// NewCacheResolver New CacheResolver
func NewCacheResolver() *CacheResolver {
host := &CacheResolver{store: ttlcache.NewCache()}
return host
}
// Get host from cache
func (host *CacheResolver) Get(domain string) (*Record, error) {
record, ok := host.store.Get(domain)
if !ok {
return nil, errors.New("not found")
}
Logger.Debugf("[HitCache] Get record of domain %s from cache.", domain)
return record.(*Record), nil
}
// All Get all hosts
func (host *CacheResolver) All() []*Record {
allKeys := host.store.Items()
all := make([]*Record, len(allKeys))
for key := range allKeys {
record, err := host.Get(key)
if err == nil {
all = append(all, record)
}
}
return all
}
// Clear Purge hosts
func (host *CacheResolver) Clear() {
host.store = ttlcache.NewCache()
}
// Set host with given Record
func (host *CacheResolver) Set(domain string, record *Record) error {
host.store.SetWithTTL(domain, record, time.Duration(record.TTL)*time.Second)
return nil
}