Skip to content

Commit

Permalink
add redis refresh & makemap safe
Browse files Browse the repository at this point in the history
  • Loading branch information
longweijin committed Aug 18, 2016
1 parent b86abe9 commit 82f3250
Showing 1 changed file with 6 additions and 10 deletions.
16 changes: 6 additions & 10 deletions hosts.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,10 +116,12 @@ func (r *RedisHosts) Set(domain, ip string) (bool, error) {
}

func (r *RedisHosts) Refresh() {
err := r.redis.Hgetall(r.key, r.hosts)
hosts := make(map[string]string) // be safe to makemap
err := r.redis.Hgetall(r.key, hosts)
if err != nil {
logger.Warn("Update hosts records from redis failed %s", err)
} else {
r.hosts = hosts
logger.Debug("Update hosts records from redis")
}
}
Expand All @@ -145,8 +147,7 @@ func (f *FileHosts) Refresh() {
}
defer buf.Close()

f.clear()

hosts := make(map[string]string) // be safe to makemap
scanner := bufio.NewScanner(buf)
for scanner.Scan() {

Expand All @@ -168,26 +169,21 @@ func (f *FileHosts) Refresh() {

domain := sli[len(sli)-1]
ip := sli[0]
// if !f.isDomain(domain) || !f.isIP(ip) {
if !f.isIP(ip) {
continue
}

f.hosts[strings.ToLower(domain)] = ip
hosts[strings.ToLower(domain)] = ip
}
f.hosts = hosts
logger.Debug("update hosts records from %s", f.file)
}

func (f *FileHosts) clear() {
f.hosts = make(map[string]string)
}

func (f *FileHosts) isDomain(domain string) bool {
if f.isIP(domain) {
return false
}
match, _ := regexp.MatchString(`^([a-zA-Z0-9\*]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$`, domain)
// match, _ := regexp.MatchString(`^([a-zA-Z0-9\*]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?)+[a-zA-Z]{2,6}$`, domain)
return match
}

Expand Down

0 comments on commit 82f3250

Please sign in to comment.