-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchecked_url.go
87 lines (72 loc) · 1.52 KB
/
checked_url.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
package dyatl
import (
"context"
"net"
"net/url"
"strings"
"time"
"golang.org/x/net/idna"
)
var DefaultDNS = "8.8.8.8:53"
func NewCheckedURL(s string) *CheckedURL {
var u CheckedURL
u.URL, u.err = url.Parse(s)
return &u
}
var dnsResolver = &net.Resolver{
PreferGo: true,
Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
d := net.Dialer{
Timeout: time.Second,
}
return d.DialContext(ctx, "udp", DefaultDNS)
},
}
type CheckedURL struct {
*url.URL
err error
}
func (u CheckedURL) LooksCorrect() bool {
if u.err != nil {
return false
}
host := u.Hostname()
if hasMajorTLD(host) && (u.Scheme == "http" || u.Scheme == "https" || u.Scheme == "ftp") && !strings.HasPrefix(host, ".") {
return true
}
return net.ParseIP(host) != nil
}
func (u CheckedURL) HostAvailable() bool {
if u.err != nil {
return false
}
ips, _ := dnsResolver.LookupIPAddr(context.Background(), u.Hostname())
if len(ips) > 0 {
return true
}
if asciiHost := u.asciiHost(); asciiHost != "" {
ips, _ := dnsResolver.LookupIPAddr(context.Background(), asciiHost)
if len(ips) > 0 {
return true
}
}
return false
}
func (u CheckedURL) asciiHost() string {
host := u.Hostname()
asciiHost, err := idna.ToASCII(host)
if err != nil || asciiHost == host {
return ""
}
return asciiHost
}
func hasMajorTLD(s string) bool {
s = strings.TrimSuffix(s, ".")
if s == "" {
return false
}
bits := strings.Split(s, ".")
domain := strings.ToUpper(bits[len(bits)-1])
_, ok := majorTLDs[domain]
return ok
}