-
Notifications
You must be signed in to change notification settings - Fork 0
/
hosts_writer.go
65 lines (49 loc) · 1.15 KB
/
hosts_writer.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
package main
import (
"fmt"
"io/ioutil"
"os"
"regexp"
)
func (app *App) startHostsWriter() {
fmt.Println("Starting hosts file writer")
app.emitter.On("domains-updated", app.updateHostsFile)
}
func (app *App) updateHostsFile() {
cleanOldRecords(app)
writeNewRecords(app)
}
func cleanOldRecords(app *App) {
hosts, err := ioutil.ReadFile(*app.hostsFile)
if err != nil {
panic(err)
}
re := regexp.MustCompile("(?m)^.*" + "docker-resolver" + ".*$[\n]+")
text := re.ReplaceAllString(string(hosts), "")
f, err := os.OpenFile(*app.hostsFile, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0600)
if err != nil {
panic(err)
}
defer f.Close()
if _, err = f.WriteString(text); err != nil {
panic(err)
}
}
func writeNewRecords(app *App) {
f, err := os.OpenFile(*app.hostsFile, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
panic(err)
}
defer f.Close()
text := createHostsString(app)
if _, err = f.WriteString(text); err != nil {
panic(err)
}
}
func createHostsString(app *App) string {
text := ""
for domain, ip := range app.records {
text = text + fmt.Sprintf("%s %s # added by docker-resolver\n", ip, domain)
}
return text
}