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
/
Copy pathdocument.go
93 lines (71 loc) · 1.68 KB
/
document.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 fragments
import (
"sync"
"github.com/PuerkitoBio/goquery"
"github.com/gofiber/fiber/v2"
"golang.org/x/net/html"
)
// Document ...
type Document struct {
doc *goquery.Document
html *HtmlFragment
statusCode int
sync.RWMutex
}
// NewDocument ...
func NewDocument(root *html.Node) (*Document, error) {
d := new(Document)
// set the default status code
d.statusCode = fiber.StatusOK
html, err := NewHtmlFragment(root)
if err != nil {
return nil, err
}
d.html = html
return d, nil
}
// Html is returning the final HTML output.
func (d *Document) Html() (string, error) {
d.RLock()
defer d.RUnlock()
html, err := d.html.Html()
if err != nil {
return "", err
}
return html, nil
}
// Fragments is returning the selection of fragments
// from an HTML page.
func (d *Document) Fragments() ([]*Fragment, error) {
d.RLock()
defer d.RUnlock()
scripts := d.doc.Find("head script[type=fragment]")
fragments := d.doc.Find("fragment").AddSelection(scripts)
ff := make([]*Fragment, 0, fragments.Length())
fragments.Each(func(i int, s *goquery.Selection) {
f := FromSelection(s)
if !f.deferred {
ff = append(ff, f)
}
})
return ff, nil
}
// Fragments is returning the selection of fragments
// from an HTML page.
func (d *Document) HtmlFragment() *HtmlFragment {
d.RLock()
defer d.RUnlock()
return d.html
}
// SetStatusCode is setting the HTTP status code for the document.
func (d *Document) SetStatusCode(status int) {
d.Lock()
defer d.Unlock() // could do this atomic
d.statusCode = status
}
// StatusCode is getting the HTTP status code for the document.
func (d *Document) StatusCode() int {
d.RLock()
defer d.RUnlock()
return d.statusCode
}