-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
121 lines (93 loc) · 1.95 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package main
import (
"flag"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"crawler/db"
"crawler/model"
"crawler/website"
"golang.org/x/net/html"
)
var (
link string
action string
)
func init() {
flag.StringVar(&link, "url", "https://aprendagolang.com.br", "url para iniciar visitas")
flag.StringVar(&action, "action", "website", "qual serviço iniciar")
}
func main() {
flag.Parse()
switch action {
case "website":
website.Run()
case "webcrawler":
done := make(chan bool)
go visitUrl(link)
<-done
default:
fmt.Printf("action '%s' não reconhecida\n", action)
}
}
func visitUrl(url string) {
if checkIfVisited(url) {
return
}
fmt.Println(url)
res, err := http.Get(url)
if err != nil {
panic(err)
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
fmt.Sprintln("status diferente de 200: %d", res.StatusCode)
return
}
htmlTree, err := html.Parse(res.Body)
if err != nil {
panic(err)
}
links := buildResult(htmlTree)
fmt.Println(len(links))
}
func checkIfVisited(url string) bool {
fmt.Printf("Visitando link: %s\n", url)
if db.IsLinkVisited(url) {
return true
}
fmt.Printf("Link já visitado: %s\n", url)
return false
}
func buildResult(htmlTree *html.Node) []string {
links := []string{}
extractLinks(htmlTree, &links)
return links
}
func extractLinks(node *html.Node, links *[]string) {
if node.Type == html.ElementNode && node.Data == "a" {
for _, attr := range node.Attr {
if attr.Key != "href" {
continue
}
link, err := url.Parse(attr.Val)
if err != nil || !strings.HasPrefix(link.Scheme, "http") {
continue
}
url := link.String()
visitedLink := model.VisitedLink{
Website: link.Host,
Link: link.String(),
VisitedDate: time.Now(),
}
*links = append(*links, url)
db.Insert("links", visitedLink)
visitUrl(url)
}
}
for child := node.FirstChild; child != nil; child = child.NextSibling {
extractLinks(child, links)
}
}