From ccb72deec76a32e25306764709cb9bfbc1528f61 Mon Sep 17 00:00:00 2001 From: bigeagle Date: Tue, 3 Feb 2015 23:03:47 +0800 Subject: [PATCH] add option to disable redis --- godns.conf | 1 + hosts.go | 20 ++++++++++++++++++-- settings.go | 9 +++++---- 3 files changed, 24 insertions(+), 6 deletions(-) diff --git a/godns.conf b/godns.conf index 7ce4b6e..a6e7bbc 100644 --- a/godns.conf +++ b/godns.conf @@ -37,6 +37,7 @@ maxcount = 0 #If set zero. The Sum of cache itmes will be unlimit. #If set false, will not query hosts file and redis hosts record enable = false host-file = "/etc/hosts" +redis-enable = true redis-key = "godns:hosts" ttl = 600 diff --git a/hosts.go b/hosts.go index 17d6445..1208eb6 100644 --- a/hosts.go +++ b/hosts.go @@ -2,6 +2,7 @@ package main import ( "bufio" + "errors" "net" "os" "regexp" @@ -17,8 +18,14 @@ type Hosts struct { func NewHosts(hs HostsSettings, rs RedisSettings) Hosts { fileHosts := &FileHosts{hs.HostsFile} - redis := &redis.Client{Addr: rs.Addr(), Db: rs.DB, Password: rs.Password} - redisHosts := &RedisHosts{redis, hs.RedisKey} + + var rc *redis.Client + if hs.RedisEnable { + rc = &redis.Client{Addr: rs.Addr(), Db: rs.DB, Password: rs.Password} + } else { + rc = nil + } + redisHosts := &RedisHosts{rc, hs.RedisKey} hosts := Hosts{fileHosts.GetAll(), redisHosts} return hosts @@ -69,17 +76,26 @@ type RedisHosts struct { } func (r *RedisHosts) GetAll() map[string]string { + if r.redis == nil { + return map[string]string{} + } var hosts = make(map[string]string) r.redis.Hgetall(r.key, hosts) return hosts } func (r *RedisHosts) Get(domain string) (ip string, ok bool) { + if r.redis == nil { + return "", false + } b, err := r.redis.Hget(r.key, domain) return string(b), err == nil } func (r *RedisHosts) Set(domain, ip string) (bool, error) { + if r.redis == nil { + return false, errors.New("Redis not enabled") + } return r.redis.Hset(r.key, domain, []byte(ip)) } diff --git a/settings.go b/settings.go index c729b8d..f9f6751 100644 --- a/settings.go +++ b/settings.go @@ -55,10 +55,11 @@ type CacheSettings struct { } type HostsSettings struct { - Enable bool - HostsFile string `toml:"host-file"` - RedisKey string `toml:"redis-key"` - TTL uint32 `toml:"ttl"` + Enable bool + HostsFile string `toml:"host-file"` + RedisEnable bool `toml:"redis-enable"` + RedisKey string `toml:"redis-key"` + TTL uint32 `toml:"ttl"` } func init() {