forked from kenshinx/godns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhosts.go
124 lines (99 loc) · 2.32 KB
/
hosts.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package main
import (
"bufio"
"github.com/hoisie/redis"
"os"
"regexp"
"strings"
)
type Hosts struct {
FileHosts map[string]string
RedisHosts *RedisHosts
}
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}
hosts := Hosts{fileHosts.GetAll(), redisHosts}
return hosts
}
/*
1. Resolve hosts file only one times
2. Request redis on every query called, not found performance lose serious yet.
3. Match local /etc/hosts file first, remote redis records second
*/
func (h *Hosts) Get(domain string) (ip string, ok bool) {
if ip, ok = h.FileHosts[domain]; ok {
return
}
if ip, ok = h.RedisHosts.Get(domain); ok {
return
}
return "", false
}
func (h *Hosts) GetAll() map[string]string {
m := make(map[string]string)
for domain, ip := range h.RedisHosts.GetAll() {
m[domain] = ip
}
for domain, ip := range h.FileHosts {
m[domain] = ip
}
return m
}
type RedisHosts struct {
redis *redis.Client
key string
}
func (r *RedisHosts) GetAll() 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) {
b, err := r.redis.Hget(r.key, domain)
return string(b), err == nil
}
func (r *RedisHosts) Set(domain, ip string) (bool, error) {
return r.redis.Hset(r.key, domain, []byte(ip))
}
type FileHosts struct {
file string
}
func (f *FileHosts) GetAll() map[string]string {
var hosts = make(map[string]string)
buf, err := os.Open(f.file)
if err != nil {
panic("Can't open " + f.file)
}
scanner := bufio.NewScanner(buf)
for scanner.Scan() {
line := scanner.Text()
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "#") || line == "" {
continue
}
sli := strings.Split(line, " ")
if len(sli) == 1 {
sli = strings.Split(line, "\t")
}
if len(sli) < 2 {
continue
}
domain := sli[len(sli)-1]
ip := sli[0]
if !f.isDomain(domain) || !f.isIP(ip) {
continue
}
hosts[domain] = ip
}
return hosts
}
func (f *FileHosts) isDomain(domain string) bool {
match, _ := regexp.MatchString("^[a-z]", domain)
return match
}
func (f *FileHosts) isIP(ip string) bool {
match, _ := regexp.MatchString("^[1-9]", ip)
return match
}