From 0dfc4bf1005171954c3bdc6afae132cbec9ae548 Mon Sep 17 00:00:00 2001 From: kenshin Date: Wed, 24 Jul 2013 19:01:31 +0800 Subject: [PATCH] refactor memory cache into map[string]dns.Msg --- cache.go | 27 ++++++++++++++------------- handler.go | 8 +++----- 2 files changed, 17 insertions(+), 18 deletions(-) diff --git a/cache.go b/cache.go index 8eca8ed..9a996cf 100644 --- a/cache.go +++ b/cache.go @@ -47,24 +47,24 @@ type Cache interface { } type MemoryCache struct { - backend map[string]string + backend map[string]*dns.Msg serializer *JsonSerializer expire time.Duration maxcount int } func (c *MemoryCache) Get(key string) (*dns.Msg, error) { - fmt.Println(c.backend) - data, ok := c.backend[key] + + mesg, ok := c.backend[key] if !ok { return nil, KeyNotFound{key} } - mesg := new(dns.Msg) - if err := c.serializer.Loads([]byte(data), &mesg); err != nil { - fmt.Println(err) - return nil, SerializerError{} - } + // mesg := new(dns.Msg) + // if err := c.serializer.Loads([]byte(data), &mesg); err != nil { + // fmt.Println(err) + // return nil, SerializerError{} + // } return mesg, nil } @@ -73,13 +73,14 @@ func (c *MemoryCache) Set(key string, mesg *dns.Msg) error { if c.Full() && !c.Exists(key) { return CacheIsFull{} } - data, err := c.serializer.Dumps(mesg) + // data, err := c.serializer.Dumps(mesg) - if err != nil { - return SerializerError{} - } + // if err != nil { + // return SerializerError{} + // } - c.backend[key] = string(data) + // c.backend[key] = string(data) + c.backend[key] = mesg return nil } diff --git a/handler.go b/handler.go index 07d6faa..d2877ce 100644 --- a/handler.go +++ b/handler.go @@ -2,8 +2,6 @@ package main import ( "github.com/miekg/dns" - // "log" - "fmt" ) type Question struct { @@ -44,14 +42,14 @@ func NewHandler() *GODNSHandler { switch cacheConfig.Backend { case "memory": cache = &MemoryCache{ - backend: make(map[string]string), + backend: make(map[string]*dns.Msg), serializer: new(JsonSerializer), expire: cacheConfig.Expire, maxcount: cacheConfig.Maxcount, } case "redis": cache = &MemoryCache{ - backend: make(map[string]string), + backend: make(map[string]*dns.Msg), serializer: new(JsonSerializer), expire: cacheConfig.Expire, maxcount: cacheConfig.Maxcount, @@ -71,7 +69,6 @@ func (h *GODNSHandler) do(net string, w dns.ResponseWriter, req *dns.Msg) { Debug("Question: %s", Q.String()) key := KeyGen(Q) - fmt.Println(key) // Only query cache when qtype == 'A' , qclass == 'IN' if q.Qtype == dns.TypeA && q.Qclass == dns.ClassINET { mesg, err := h.cache.Get(key) @@ -79,6 +76,7 @@ func (h *GODNSHandler) do(net string, w dns.ResponseWriter, req *dns.Msg) { Debug("%s didn't hit cache: %s", Q.String(), err) } else { Debug("%s hit cache", Q.String()) + mesg.Id = req.Id w.WriteMsg(mesg) return }