-
Notifications
You must be signed in to change notification settings - Fork 10
/
hostfile.go
53 lines (48 loc) · 938 Bytes
/
hostfile.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
package main
import (
"io/ioutil"
"log"
"net"
"path"
"strconv"
"strings"
)
type ipTtl struct {
IP net.IP
TTL uint32
}
type Hosts map[string]ipTtl
func ParseHost(filename string, hosts Hosts) {
ttl, err := strconv.Atoi(strings.Replace(path.Ext(filename), ".", "", -1))
if err != nil || ttl == 0 {
ttl = 600
}
data, err := ioutil.ReadFile(filename)
if err != nil {
log.Println("[WARN] open hosts fila failed", err)
return
}
for _, line := range strings.Split(string(data), "\n") {
if strings.HasPrefix(line, "#") {
continue
}
fields := strings.Fields(line)
if len(fields) < 2 {
continue
}
ip := net.ParseIP(fields[0])
if ip == nil {
continue
}
for _, domain := range fields[1:] {
hosts[domain] = ipTtl{IP: ip, TTL: uint32(ttl)}
}
}
}
func ParseHostsFiles(filenames []string) (hosts Hosts) {
hosts = make(Hosts)
for _, fn := range filenames {
ParseHost(fn, hosts)
}
return
}