-
Notifications
You must be signed in to change notification settings - Fork 18
/
helpers.go
77 lines (66 loc) · 1.72 KB
/
helpers.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
package rules
import (
"strings"
"golang.org/x/net/publicsuffix"
)
// splitWithEscapeCharacter splits string by the specified separator if it is not escaped
func splitWithEscapeCharacter(str string, sep, escapeCharacter byte, preserveAllTokens bool) []string {
parts := make([]string, 0)
if str == "" {
return parts
}
var sb strings.Builder
escaped := false
for i := range str {
c := str[i]
if c == escapeCharacter {
escaped = true
} else if c == sep {
if escaped {
sb.WriteByte(c)
escaped = false
} else {
if preserveAllTokens || sb.Len() > 0 {
parts = append(parts, sb.String())
sb.Reset()
}
}
} else {
if escaped {
escaped = false
sb.WriteByte(escapeCharacter)
}
sb.WriteByte(c)
}
}
if preserveAllTokens || sb.Len() > 0 {
parts = append(parts, sb.String())
}
return parts
}
// isDomainOrSubdomainOfAny checks if "domain" is domain or subdomain or any of the "domains"
func isDomainOrSubdomainOfAny(domain string, domains []string) bool {
for _, d := range domains {
if strings.HasSuffix(d, ".*") {
// A pattern like "google.*" will match any "google.TLD" domain or subdomain
withoutWildcard := d[0 : len(d)-1]
if strings.HasPrefix(domain, withoutWildcard) ||
(strings.Index(domain, withoutWildcard) > 0 &&
strings.Index(domain, "."+withoutWildcard) > 0) {
tld, icann := publicsuffix.PublicSuffix(domain)
// Let's check that the domain's TLD is one of the public suffixes
if tld != "" && icann &&
strings.HasSuffix(domain, withoutWildcard+tld) {
return true
}
}
} else {
if domain == d ||
(strings.HasSuffix(domain, d) &&
strings.HasSuffix(domain, "."+d)) {
return true
}
}
}
return false
}