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
/
fragment.go
294 lines (230 loc) · 5.76 KB
/
fragment.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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
package fragments
import (
"bytes"
"strconv"
"strings"
"sync"
"time"
"github.com/PuerkitoBio/goquery"
"github.com/gofiber/fiber/v2"
"github.com/google/uuid"
"github.com/valyala/fasthttp"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
// HtmlFragment is representation of HTML fragments.
type HtmlFragment struct {
doc *goquery.Document
sync.RWMutex
}
// NewHtmlFragment creates a new fragment of HTML.
func NewHtmlFragment(root *html.Node) (*HtmlFragment, error) {
h := new(HtmlFragment)
h.doc = goquery.NewDocumentFromNode(root)
return h, nil
}
// Document get the full document representation
// of the HTML fragment.
func (h *HtmlFragment) Fragment() *goquery.Document {
return h.doc
}
// Fragments is returning the selection of fragments
// from an HTML page.
func (h *HtmlFragment) Fragments() (map[string]*Fragment, error) {
h.RLock()
defer h.RUnlock()
scripts := h.doc.Find("head script[type=fragment]")
fragments := h.doc.Find("fragment").AddSelection(scripts)
ff := make(map[string]*Fragment)
fragments.Each(func(i int, s *goquery.Selection) {
f := FromSelection(s)
if !f.deferred {
ff[f.ID()] = f
}
})
return ff, nil
}
// Html creates the HTML output of the created document.
func (h *HtmlFragment) Html() (string, error) {
h.RLock()
defer h.RUnlock()
html, err := h.doc.Html()
if err != nil {
return "", err
}
return html, nil
}
// AppendHead ...
func (d *HtmlFragment) AppendHead(ns ...*html.Node) {
head := d.doc.Find("head")
head.AppendNodes(ns...)
}
// Fragment is a <fragment> in the <header> or <body>
// of a HTML page.
type Fragment struct {
deferred bool
fallback string
method string
primary bool
src string
timeout int64
id string
ref string
statusCode int
head []*html.Node
f *HtmlFragment
s *goquery.Selection
}
// FromSelection creates a new fragment from a
// fragment selection in the DOM.
func FromSelection(s *goquery.Selection) *Fragment {
f := new(Fragment)
f.s = s
src, _ := s.Attr("src")
f.src = src
fallback, _ := s.Attr("fallback")
f.fallback = fallback
method, _ := s.Attr("method")
f.method = method
timeout, ok := s.Attr("timeout")
if !ok {
timeout = "60"
}
t, _ := strconv.ParseInt(timeout, 10, 64)
f.timeout = t
id, ok := s.Attr("id")
if !ok {
id = uuid.New().String()
}
f.id = id
ref, _ := s.Attr("ref")
f.ref = ref
deferred, ok := s.Attr("deferred")
f.deferred = ok && strings.ToUpper(deferred) != "FALSE"
primary, ok := s.Attr("primary")
f.primary = ok && strings.ToUpper(primary) != "FALSE"
f.head = make([]*html.Node, 0)
return f
}
// Src is the URL for the fragment.
func (f *Fragment) Src() string {
return f.src
}
// Fallback is the fallback URL for the fragment.
func (f *Fragment) Fallback() string {
return f.fallback
}
// Timeout is the timeout for fetching the fragment.
func (f *Fragment) Timeout() time.Duration {
return time.Duration(f.timeout) * time.Second
}
// Method is the HTTP method to use for fetching the fragment.
func (f *Fragment) Method() string {
return f.method
}
// Element is a pointer to the selected element in the DOM.
func (f *Fragment) Element() *goquery.Selection {
return f.s
}
// Deferred is deferring the fetching to the browser.
func (f *Fragment) Deferred() bool {
return f.deferred
}
// Primary denotes a fragment as responsible for setting
// the response code of the entire HTML page.
func (f *Fragment) Primary() bool {
return f.primary
}
// Links returns the new nodes that go in the head via
// the LINK HTTP header entity.
func (f *Fragment) Links() []*html.Node {
return f.head
}
// Ref represents the reference to another fragment
func (f *Fragment) Ref() string {
return f.ref
}
// ID represents a unique id for the fragment
func (f *Fragment) ID() string {
return f.id
}
// HtmlFragment returns embedded fragments of HTML.
func (f *Fragment) HtmlFragment() *HtmlFragment {
return f.f
}
// Resolve is resolving all needed data, setting headers
// and the status code.
func (f *Fragment) Resolve() ResolverFunc {
return func(c *fiber.Ctx, cfg Config) error {
err := f.do(c, cfg, f.src)
if err == nil {
return err
}
if err != fasthttp.ErrTimeout {
return err
}
err = f.do(c, cfg, f.fallback)
if err != nil {
return err
}
return nil
}
}
func (f *Fragment) do(c *fiber.Ctx, cfg Config, src string) error {
req := fasthttp.AcquireRequest()
res := fasthttp.AcquireResponse()
defer fasthttp.ReleaseRequest(req)
defer fasthttp.ReleaseResponse(res)
c.Request().CopyTo(req)
uri := fasthttp.AcquireURI()
defer fasthttp.ReleaseURI(uri)
if err := uri.Parse(nil, []byte(src)); err != nil {
return err
}
if len(uri.Host()) == 0 {
uri.SetHost(cfg.DefaultHost)
}
req.SetRequestURI(uri.String())
req.Header.Del(fiber.HeaderConnection)
t := f.Timeout()
if err := client.DoTimeout(req, res, t); err != nil {
return err
}
res = cfg.FilterResponse(res)
f.statusCode = res.StatusCode()
// if res.StatusCode() != http.StatusOK {
// // TODO: wrap in custom error, to not replace
// return fmt.Errorf("resolve: could not resolve fragment at %s", f.Src())
// }
res.Header.Del(fiber.HeaderConnection)
contentEncoding := res.Header.Peek("Content-Encoding")
body := res.Body()
var err error
if bytes.EqualFold(contentEncoding, []byte("gzip")) {
body, err = res.BodyGunzip()
if err != nil {
return cfg.ErrorHandler(c, err)
}
}
h := Header(string(res.Header.Peek("link")))
nodes := CreateNodes(h.Links())
f.head = append(f.head, nodes...)
root := &html.Node{
Type: html.ElementNode,
DataAtom: atom.Body,
Data: "body",
}
ns, err := html.ParseFragment(bytes.NewReader(body), root)
if err != nil {
return err
}
for _, n := range ns {
root.AppendChild(n)
}
doc, err := NewHtmlFragment(root)
if err != nil {
return nil
}
f.f = doc
return nil
}