/
rich_url.go
53 lines (44 loc) · 968 Bytes
/
rich_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
package goreferrer
import (
"net/url"
"strings"
"golang.org/x/net/publicsuffix"
)
type richUrl struct {
*url.URL
Subdomain string
Domain string
Tld string
}
func parseRichUrl(s string) (*richUrl, bool) {
u, err := url.Parse(s)
if err != nil {
return nil, false
}
// assume a default scheme of http://
if u.Scheme == "" {
s = "http://" + s
u, err = url.Parse(s)
if err != nil {
return nil, false
}
}
tld, _ := publicsuffix.PublicSuffix(u.Host)
if tld == "" || len(u.Host)-len(tld) < 2 {
return nil, false
}
hostWithoutTld := u.Host[:len(u.Host)-len(tld)-1]
lastDot := strings.LastIndex(hostWithoutTld, ".")
if lastDot == -1 {
return &richUrl{URL: u, Domain: hostWithoutTld, Tld: tld}, true
}
return &richUrl{
URL: u,
Subdomain: hostWithoutTld[:lastDot],
Domain: hostWithoutTld[lastDot+1:],
Tld: tld,
}, true
}
func (u *richUrl) RegisteredDomain() string {
return u.Domain + "." + u.Tld
}