add option to disable redis

This commit is contained in:
bigeagle 2015-02-03 23:03:47 +08:00
parent 624a46fddc
commit 952f39ddf2
3 changed files with 20 additions and 2 deletions

View File

@ -17,6 +17,7 @@ timeout = 5 # 5 seconds
domain-server-file = "/etc/godns.d/servers" domain-server-file = "/etc/godns.d/servers"
[redis] [redis]
enable = true
host = "127.0.0.1" host = "127.0.0.1"
port = 6379 port = 6379
db = 0 db = 0

View File

@ -2,6 +2,7 @@ package main
import ( import (
"bufio" "bufio"
"errors"
"net" "net"
"os" "os"
"regexp" "regexp"
@ -17,8 +18,14 @@ type Hosts struct {
func NewHosts(hs HostsSettings, rs RedisSettings) Hosts { func NewHosts(hs HostsSettings, rs RedisSettings) Hosts {
fileHosts := &FileHosts{hs.HostsFile} 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 rs.Enable {
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} hosts := Hosts{fileHosts.GetAll(), redisHosts}
return hosts return hosts
@ -69,17 +76,26 @@ type RedisHosts struct {
} }
func (r *RedisHosts) GetAll() map[string]string { func (r *RedisHosts) GetAll() map[string]string {
if r.redis == nil {
return map[string]string{}
}
var hosts = make(map[string]string) var hosts = make(map[string]string)
r.redis.Hgetall(r.key, hosts) r.redis.Hgetall(r.key, hosts)
return hosts return hosts
} }
func (r *RedisHosts) Get(domain string) (ip string, ok bool) { func (r *RedisHosts) Get(domain string) (ip string, ok bool) {
if r.redis == nil {
return "", false
}
b, err := r.redis.Hget(r.key, domain) b, err := r.redis.Hget(r.key, domain)
return string(b), err == nil return string(b), err == nil
} }
func (r *RedisHosts) Set(domain, ip string) (bool, error) { 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)) return r.redis.Hset(r.key, domain, []byte(ip))
} }

View File

@ -36,6 +36,7 @@ type DNSServerSettings struct {
} }
type RedisSettings struct { type RedisSettings struct {
Enable bool
Host string Host string
Port int Port int
DB int DB int