forked from pablokbs/peladonerd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
93 lines (78 loc) · 1.67 KB
/
app.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
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"os"
"strings"
"golang.org/x/net/html"
)
type scrapeDataStore struct {
Internal int `json:"internal"`
External int `json:"external"`
}
func isInternal(parsedLink *url.URL, siteUrl *url.URL, link string) bool {
return parsedLink.Host == siteUrl.Host || strings.Index(link, "#") == 0 || len(parsedLink.Host) == 0
}
func main() {
urlIn := os.Getenv("url")
if len(urlIn) == 0 {
urlIn = "https://www.alexellis.io/"
// log.Fatalln("Need a valid url as an env-var.")
}
siteUrl, parseErr := url.Parse(urlIn)
if parseErr != nil {
log.Fatalln(parseErr)
}
resp, err := http.Get(urlIn)
if err != nil {
log.Fatalln(err)
}
scrapeData := &scrapeDataStore{}
tokenizer := html.NewTokenizer(resp.Body)
end := false
for {
tt := tokenizer.Next()
switch {
case tt == html.StartTagToken:
// fmt.Println(tt)
token := tokenizer.Token()
switch token.Data {
case "a":
for _, attr := range token.Attr {
if attr.Key == "href" {
link := attr.Val
parsedLink, parseLinkErr := url.Parse(link)
// debug
// if strings.Index(link, "#") == 0 {
// fmt.Println(link)
// } else {
// fmt.Println(parsedLink)
// }
if parseLinkErr == nil {
if isInternal(parsedLink, siteUrl, link) {
scrapeData.Internal++
} else {
scrapeData.External++
}
}
if parseLinkErr != nil {
fmt.Println("Can't parse: " + token.Data)
}
}
}
break
}
case tt == html.ErrorToken:
end = true
break
}
if end {
break
}
}
data, _ := json.Marshal(&scrapeData)
fmt.Println(string(data))
}