From fbb898dde933b6d008b27f0258fa29ca721b4fce Mon Sep 17 00:00:00 2001 From: Dingjun Date: Tue, 8 Nov 2016 10:13:12 +0800 Subject: [PATCH] add option for enable/disable cache --- cfg.go | 1 + example_config/config.json | 1 + routers.go | 22 ++++++++++++++-------- 3 files changed, 16 insertions(+), 8 deletions(-) diff --git a/cfg.go b/cfg.go index b07d0c5..fdbed53 100644 --- a/cfg.go +++ b/cfg.go @@ -43,6 +43,7 @@ type Rule struct { } type cfg struct { + EnableCache bool `json:"enable_cache"` Listen []string `json:"listen"` User string `json:"user"` Group string `json:"group"` diff --git a/example_config/config.json b/example_config/config.json index 1a673a1..6b97200 100644 --- a/example_config/config.json +++ b/example_config/config.json @@ -5,6 +5,7 @@ "group":"nogroup", "ttl":3600, "timeout":1, + "enable_cache":false, "blacklist_ips":["ip.txt"], "rules":[ { diff --git a/routers.go b/routers.go index 3039c6e..dc85d01 100644 --- a/routers.go +++ b/routers.go @@ -46,12 +46,14 @@ func (r *routers) query(m *dns.Msg, servers []addr) (*dns.Msg, error) { var up dnsClient var lastErr error - // query cache - m2 := r.cache.get(m) - if m2 != nil { - //log.Printf("query %s, reply from cache\n", m.Question[0].Name) - m2.Id = m.Id - return m2, nil + if r.c.EnableCache { + // query cache + m2 := r.cache.get(m) + if m2 != nil { + //log.Printf("query %s, reply from cache\n", m.Question[0].Name) + m2.Id = m.Id + return m2, nil + } } for _, srv := range servers { @@ -70,7 +72,7 @@ func (r *routers) query(m *dns.Msg, servers []addr) (*dns.Msg, error) { m1, _, err := up.Exchange(m, srv.addr) if err == nil && !r.checkBlacklist(m) { - if m1.Rcode == dns.RcodeSuccess { + if m1.Rcode == dns.RcodeSuccess && r.c.EnableCache { // store to cache r.cache.set(m1) } @@ -118,11 +120,15 @@ func (r *routers) ServeDNS(w dns.ResponseWriter, m *dns.Msg) { } func initRouters(c *cfg) { + var cache1 *cache = nil + if c.EnableCache { + cache1 = newCache(1000, int64(c.TTL)) // cache 5 hours + } router := &routers{ c, &dns.Client{Net: "tcp", Timeout: time.Duration(c.Timeout) * time.Second}, &dns.Client{Net: "udp", Timeout: time.Duration(c.Timeout) * time.Second}, - newCache(1000, int64(c.TTL)), // cache 5 hours + cache1, } dns.Handle(".", router) }