-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
updateHosts.go
64 lines (58 loc) · 1.49 KB
/
updateHosts.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
//
// Update hosts for windows
//
package main
import (
"os"
"io"
"bufio"
"net/http"
"time"
"bytes"
"io/ioutil"
)
var (
HOSTS_PATH string = os.Getenv("SYSTEMROOT")+"\\system32\\drivers\\etc\\hosts"
SEARCH_STRING []byte = []byte("#TX-HOSTS")
HOSTS_SOURCE string = "https://tx.txthinking.com/hosts"
)
func main(){
var hosts []byte
f, err := os.OpenFile(HOSTS_PATH, os.O_RDONLY, 0444)
if err == nil {
bnr := bufio.NewReader(f)
for{
line, _, err := bnr.ReadLine()
if bytes.Compare(line,SEARCH_STRING)==0 || err == io.EOF{
break
}
hosts = append(hosts, append(line,[]byte("\r\n")...)...)
}
f.Close()
}
hosts = append(hosts, append(SEARCH_STRING,[]byte("\r\n")...)...)
res, err := http.Get(HOSTS_SOURCE)
if err != nil {
println(err.Error())
time.Sleep(3 * time.Second)
return
}
data, err := ioutil.ReadAll(res.Body)
if err != nil {
println(err.Error())
time.Sleep(3 * time.Second)
return
}
data = bytes.Replace(data, []byte("\n"), []byte("\r\n"), -1)
hosts = append(hosts, data...)
os.Rename(HOSTS_PATH, HOSTS_PATH+"-BAK-TX-HOSTS")
f, err = os.OpenFile(HOSTS_PATH, os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
println(err.Error())
time.Sleep(3 * time.Second)
return
}
f.Write(hosts)
println("Success!")
time.Sleep(3 * time.Second)
}