This repository has been archived by the owner on Jul 14, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
links.go
143 lines (110 loc) · 2.36 KB
/
links.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
package fragments
import (
"strings"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
const (
StyleSheet = "stylesheet"
Script = "script"
)
// Link ...
type Link struct {
URL string
Rel string
Params map[string]string
}
// Header ...
type Header string
// Link ...
func (s Header) Links() []Link {
links := make([]Link, 0)
for _, chunk := range strings.Split(string(s), ",") {
l := Link{URL: "", Rel: "", Params: make(map[string]string)}
for _, part := range strings.Split(chunk, ";") {
part = strings.Trim(part, " ")
if part == "" {
continue
}
if part[0] == '<' && part[len(part)-1] == '>' {
l.URL = strings.Trim(part, "<>")
continue
}
key, val := parseParam(part)
if key == "" {
continue
}
if strings.ToLower(key) == "rel" {
l.Rel = val
continue
}
l.Params[key] = val
}
if l.URL != "" {
links = append(links, l)
}
}
return links
}
// FilterByStylesheet ...
func FilterByStylesheet(links ...Link) []Link {
return FilterByRel(links, "stylesheet")
}
// FilterByStylesheet ...
func FilterByScript(links ...Link) []Link {
return FilterByRel(links, "script")
}
// FilterByRel ...
func FilterByRel(links []Link, rel string) []Link {
ll := make([]Link, 0)
for _, l := range links {
if l.Rel != rel {
continue
}
ll = append(ll, l)
}
return ll
}
// CreateNodes ...
func CreateNodes(links []Link) []*html.Node {
nodes := make([]*html.Node, 0)
for _, s := range links {
attr := make([]html.Attribute, 0)
if s.Rel == Script {
attr = append(attr, html.Attribute{Key: "src", Val: s.URL})
}
if s.Rel == StyleSheet {
attr = append(attr, html.Attribute{Key: "href", Val: s.URL})
attr = append(attr, html.Attribute{Key: "rel", Val: s.Rel})
}
for k, p := range s.Params {
attr = append(attr, html.Attribute{Key: k, Val: p})
}
node := &html.Node{
Type: html.ElementNode,
Attr: attr,
}
if s.Rel == "script" {
node.Data = "script"
node.DataAtom = atom.Script
}
if s.Rel == "stylesheet" {
node.Data = "link"
node.DataAtom = atom.Link
}
nodes = append(nodes, node)
}
return nodes
}
func parseParam(raw string) (key, val string) {
parts := strings.SplitN(raw, "=", 2)
if len(parts) == 1 {
return parts[0], ""
}
if len(parts) != 2 {
return "", ""
}
key = parts[0]
val = strings.Trim(parts[1], "\"")
return key, val
}