-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhtml.go
111 lines (94 loc) · 2 KB
/
html.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
package main
import (
"net/http"
"net/url"
"golang.org/x/net/html"
)
func fromHtml(ctx Context, res *http.Response) {
Info(ctx.Depth, "Processing HTML...")
parsedHtml, err := html.Parse(res.Body)
if err != nil {
Error(ctx.Depth, "Failed to parse HTML:", err)
return
}
isScript := false
script := ""
isStyle := false
style := ""
var walk func(*html.Node)
walk = func(node *html.Node) {
if node.Type == html.ElementNode {
// js source maps
if node.Data == "script" {
isScript = true
for _, attr := range node.Attr {
// <script src="...">
if attr.Key == "src" {
script = attr.Val
break
}
}
}
// css source maps
if node.Data == "link" {
for _, attr := range node.Attr {
// <link rel="stylesheet">
if attr.Key == "rel" && attr.Val == "stylesheet" {
isStyle = true
break
}
// <link as="style">
if attr.Key == "as" && attr.Val == "style" {
isStyle = true
break
}
// <link as="script">
if attr.Key == "as" && attr.Val == "script" {
isScript = true
break
}
}
for _, attr := range node.Attr {
// <link href="...">
if attr.Key == "href" {
style = attr.Val
script = attr.Val
break
}
}
}
}
if isScript && script != "" {
ref, err := ctx.Url.Parse(script)
if err != nil {
Error(ctx.Depth, "Failed to parse JavaScript url:", err)
} else {
jsCtx := ctx
jsCtx.Url = *ctx.Url.ResolveReference(ref)
jsCtx.Depth++
js, ok := fetch(jsCtx)
if ok {
fromJs(jsCtx, js)
}
}
}
if isStyle && style != "" {
ref, err := url.Parse(style)
if err != nil {
Error(ctx.Depth, "Failed to parse CSS url:", err)
} else {
cssCtx := ctx
cssCtx.Url = *ctx.Url.ResolveReference(ref)
cssCtx.Depth++
css, ok := fetch(cssCtx)
if ok {
fromCss(cssCtx, css)
}
}
}
for child := node.FirstChild; child != nil; child = child.NextSibling {
walk(child)
}
}
walk(parsedHtml)
}