-
Notifications
You must be signed in to change notification settings - Fork 0
/
GetLinks.go
82 lines (69 loc) · 2.5 KB
/
GetLinks.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
package katsuragi
import (
"fmt"
"net/url"
"golang.org/x/net/html"
)
// GetLinks fetches links from the given URL based on the category ("all", "internal", "external")
func (f *Fetcher) GetLinks(props GetLinksProps) ([]string, error) {
// Set default category to "all"
if props.Category == "" {
props.Category = "all"
}
doc, err := retrieveHTML(props.Url, f)
if err != nil {
return nil, err
}
var links []string
baseUrl, _ := url.Parse(props.Url)
// *The error is ignored because the URL has been already validated in retrieveHTML.
var traverse func(*html.Node)
traverse = func(n *html.Node) {
if n.Type == html.ElementNode && n.Data == "a" {
for _, a := range n.Attr {
if a.Key == "href" {
// will be tested using bad links in html
href, err := url.Parse(a.Val)
if err != nil {
continue
}
// absolute href (if relative, returns the same if not)
resolvedUrl := baseUrl.ResolveReference(href).String()
// base domain
baseUrlParts, _ := extractDomainParts(props.Url)
// *The error is ignored because the URL has been already validated in retrieveHTML.
// link domain
resolvedUrlParts, err := extractDomainParts(resolvedUrl)
if err != nil {
return
}
baseUrlDomain := baseUrlParts.Root + "." + baseUrlParts.TLD
resolvedUrlDomain := resolvedUrlParts.Root + "." + resolvedUrlParts.TLD
// Url.host will be different in cases like "http://example.com" and "http://www.example.com",
// so we need to compare the domains instead.
switch props.Category {
case "all":
links = append(links, resolvedUrl)
case "internal":
if resolvedUrlDomain == "" || resolvedUrlDomain == baseUrlDomain {
links = append(links, resolvedUrl)
}
case "external":
if resolvedUrlDomain != "" && resolvedUrlDomain != baseUrlDomain {
links = append(links, resolvedUrl)
}
}
break
}
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
traverse(c)
}
}
traverse(doc)
if len(links) == 0 {
return nil, fmt.Errorf("GetTitle failed to find any links in HTML")
}
return links, nil
}