Use pack and unpack from dns library.

This commit is contained in:
Dhananjay Balan 2016-02-13 15:25:19 +05:30
parent 8c4b338257
commit 790acb55da
1 changed files with 16 additions and 18 deletions

View File

@ -36,10 +36,11 @@ func (e CacheIsFull) Error() string {
} }
type SerializerError struct { type SerializerError struct {
err error
} }
func (e SerializerError) Error() string { func (e SerializerError) Error() string {
return "Serializer error" return fmt.Sprintf("Serializer error: got %v", e.err)
} }
type Mesg struct { type Mesg struct {
@ -55,11 +56,6 @@ type Cache interface {
Full() bool Full() bool
} }
type Serializer interface {
Loads([]byte) (*dns.Msg, error)
Dumps(*dns.Msg) ([]byte, error)
}
type MemoryCache struct { type MemoryCache struct {
Backend map[string]Mesg Backend map[string]Mesg
Expire time.Duration Expire time.Duration
@ -132,16 +128,14 @@ Memcached backend
func NewMemcachedCache(servers []string, expire int32) *MemcachedCache { func NewMemcachedCache(servers []string, expire int32) *MemcachedCache {
c := memcache.New(servers...) c := memcache.New(servers...)
return &MemcachedCache{ return &MemcachedCache{
backend: c, backend: c,
serializer: &JsonSerializer{}, expire: expire,
expire: expire,
} }
} }
type MemcachedCache struct { type MemcachedCache struct {
backend *memcache.Client backend *memcache.Client
serializer Serializer expire int32
expire int32
} }
func (m *MemcachedCache) Set(key string, msg *dns.Msg) error { func (m *MemcachedCache) Set(key string, msg *dns.Msg) error {
@ -152,22 +146,26 @@ func (m *MemcachedCache) Set(key string, msg *dns.Msg) error {
if msg == nil { if msg == nil {
val = []byte("nil") val = []byte("nil")
} else { } else {
val, err = m.serializer.Dumps(msg) val, err = msg.Pack()
} }
if err != nil { if err != nil {
return err err = SerializerError{err}
} }
return m.backend.Set(&memcache.Item{Key: key, Value: val, Expiration: m.expire}) return m.backend.Set(&memcache.Item{Key: key, Value: val, Expiration: m.expire})
} }
func (m *MemcachedCache) Get(key string) (msg *dns.Msg, err error) { func (m *MemcachedCache) Get(key string) (*dns.Msg, error) {
var msg dns.Msg
item, err := m.backend.Get(key) item, err := m.backend.Get(key)
if err != nil { if err != nil {
err = KeyNotFound{key} err = KeyNotFound{key}
return return &msg, err
} }
msg, err = m.serializer.Loads(item.Value) err = msg.Unpack(item.Value)
return if err != nil {
err = SerializerError{err}
}
return &msg, err
} }
func (m *MemcachedCache) Exists(key string) bool { func (m *MemcachedCache) Exists(key string) bool {