-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhost.go
70 lines (56 loc) · 1.37 KB
/
host.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
package main
import (
"fmt"
"log"
"os"
"strings"
)
const hostsFilePath = `C:\Windows\System32\drivers\etc\hosts`
const loopbackAddress = "127.0.0.1"
func addToHostsFile(domain string) bool {
f, err := os.OpenFile(hostsFilePath, os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
log.Print(err)
return false
}
defer f.Close()
_, err = f.WriteString(fmt.Sprintf("%s %s\n", loopbackAddress, domain))
if err != nil {
log.Print(err)
return false
}
return true
}
func removeFromHostsFile(domain string) error {
contents, err := os.ReadFile(hostsFilePath)
if err != nil {
return err
}
lines := strings.Split(string(contents), "\n")
var newLines []string
toRemove := fmt.Sprintf("%s %s", loopbackAddress, domain)
for _, line := range lines {
if strings.TrimSpace(line) != toRemove {
newLines = append(newLines, line)
}
}
return os.WriteFile(hostsFilePath, []byte(strings.Join(newLines, "\n")), 0644)
}
func getBlockedDomains() ([]string, error) {
contents, err := os.ReadFile(hostsFilePath)
if err != nil {
return nil, err
}
lines := strings.Split(string(contents), "\n")
var blockedDomains []string
for _, line := range lines {
if strings.HasPrefix(line, loopbackAddress) {
fields := strings.Fields(line)
if len(fields) >= 2 {
domain := fields[1]
blockedDomains = append(blockedDomains, domain)
}
}
}
return blockedDomains, nil
}