-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
67 lines (61 loc) · 1.38 KB
/
main.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
package main
import (
"bufio"
"flag"
"fmt"
"os"
"strings"
"golang.org/x/net/publicsuffix"
)
func main() {
subs := flag.Bool("subs", false, "Return subdomains, not base domains")
flag.Parse()
sc := bufio.NewScanner(os.Stdin)
for sc.Scan() {
record := trimDot(sc.Text())
// ensure the TLD is valid
_, ok := publicsuffix.PublicSuffix(record)
if ok {
switch *subs {
case true:
result, _ := getSubdomain(record)
if len(result) != 0 {
fmt.Println(result)
}
case false:
result, _ := getETLDPlusOne(record)
if len(result) != 0 {
fmt.Println(result)
}
}
}
}
}
// getETLDPlusOne returns the base domain.
// "www.toys.amazon.co.uk" => "amazon.co.uk"
func getETLDPlusOne(domain string) (string, error) {
e, err := publicsuffix.EffectiveTLDPlusOne(domain)
if err != nil {
fmt.Println(err)
return "", err
}
return e, nil
}
// getSubdomain returns everything but the base domain
// "www.toys.amazon.co.uk" => "www.toys"
func getSubdomain(domain string) (string, error) {
e, err := publicsuffix.EffectiveTLDPlusOne(domain)
if err != nil {
return "", err
}
subdomain := strings.TrimSuffix(domain, e)
subdomain = strings.TrimSuffix(subdomain, ".")
return subdomain, nil
}
// trimDot removes any trailing dots
func trimDot(domain string) string {
if strings.HasSuffix(domain, ".") {
domain = strings.TrimSuffix(domain, ".")
}
return domain
}