-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfreader.go
106 lines (97 loc) · 1.92 KB
/
freader.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
package main
import (
"bufio"
"bytes"
"encoding/json"
"io"
"log"
"os"
"os/user"
"path"
"regexp"
"strings"
)
func GetDomainsFromPac(c []byte) map[string]bool {
//c, err := ioutil.ReadFile(fname)
//if err != nil {
// log.Printf("read file error %s", err)
//}
reg, err := regexp.Compile(`(?sU:\{.*\}\n\};)`)
if err != nil {
log.Printf("regex pattern compile error %s", err)
}
names := reg.Find(c)
names = bytes.TrimRight(names, ";")
var tmp map[string]map[string]int
err = json.Unmarshal(names, &tmp)
if err != nil {
log.Printf("pac file format error %s", err)
return nil
}
result := make(map[string]bool, 0)
for k, v := range tmp {
for d1, _ := range v {
domain := d1 + "." + k
result[domain] = true
}
}
return result
}
func GetDomains(fp io.Reader) []string {
scanner := bufio.NewScanner(fp)
result := make([]string, 0)
for scanner.Scan() {
l := scanner.Text()
if strings.HasPrefix(l, "#") {
continue
}
if strings.TrimSpace(l) != "" {
//log.Printf("add line %s", l)
result = append(result, l)
}
}
return result
}
//perform wildcard path match
func MatchDomain(token, pattern string) bool {
m, e := path.Match(pattern, token)
if e != nil {
log.Printf("match err %s", e)
return false
}
return m
}
func IsDomainIn(domain string, list []string) bool {
for _, p := range list {
if MatchDomain(domain, p) {
return true
}
}
return false
}
func ExpandHomePath(p string) string {
if strings.HasPrefix(p, "~") {
u, err := user.Current()
if err != nil {
log.Printf("get user err %s", err)
return p
}
part := strings.TrimLeft(p, "~")
return path.Join(u.HomeDir, part)
}
return p
}
func ShortenDomain(d string) string {
parts := strings.Split(d, ".")
l := len(parts)
if l > 2 {
return parts[l-2] + "." + parts[l-1]
}
return d
}
func IsFileExists(filename string) bool {
if _, err := os.Stat(filename); os.IsNotExist(err) {
return false
}
return true
}