mirror of
https://github.com/nadoo/glider.git
synced 2026-11-19 07:09:42 +08:00
dns: 1. support cache; 2. support custom records; #35
This commit is contained in:
1 parent
a2a67df771
commit
a226637bfb
6 files changed
+210
-58
No files matched your search
@@ -0,0 +1,69 @@
|
||||
package dns
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// HundredYears is one hundred years duration in seconds, used for none-expired items
|
||||
const HundredYears = 100 * 365 * 24 * 3600
|
||||
|
||||
type item struct {
|
||||
value []byte
|
||||
expire time.Time
|
||||
}
|
||||
|
||||
// Cache is the struct of cache
|
||||
type Cache struct {
|
||||
m map[string]*item
|
||||
l sync.RWMutex
|
||||
}
|
||||
|
||||
// NewCache returns a new cache
|
||||
func NewCache() (c *Cache) {
|
||||
c = &Cache{m: make(map[string]*item)}
|
||||
go func() {
|
||||
for now := range time.Tick(time.Second) {
|
||||
c.l.Lock()
|
||||
for k, v := range c.m {
|
||||
if now.After(v.expire) {
|
||||
delete(c.m, k)
|
||||
}
|
||||
}
|
||||
c.l.Unlock()
|
||||
}
|
||||
}()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Len returns the length of cache
|
||||
func (c *Cache) Len() int {
|
||||
return len(c.m)
|
||||
}
|
||||
|
||||
// Put an item into cache, invalid after ttl seconds, never invalid if ttl=0
|
||||
func (c *Cache) Put(k string, v []byte, ttl int) {
|
||||
if len(v) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
c.l.Lock()
|
||||
it, ok := c.m[k]
|
||||
if !ok {
|
||||
it = &item{value: v}
|
||||
c.m[k] = it
|
||||
}
|
||||
it.expire = time.Now().Add(time.Duration(ttl) * time.Second)
|
||||
c.l.Unlock()
|
||||
}
|
||||
|
||||
// Get an item from cache
|
||||
func (c *Cache) Get(k string) (v []byte) {
|
||||
c.l.RLock()
|
||||
if it, ok := c.m[k]; ok {
|
||||
v = it.value
|
||||
}
|
||||
c.l.RUnlock()
|
||||
return
|
||||
}
|
||||
Reference in new issue
Block a user