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
/
resolver.go
91 lines (69 loc) · 1.51 KB
/
resolver.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
package fragments
import (
"sync"
"github.com/gofiber/fiber/v2"
"golang.org/x/net/html"
)
// Resolver ...
type Resolver struct {
wg sync.WaitGroup
}
// NewResolver ...
func NewResolver() *Resolver {
return &Resolver{}
}
// ResolverFunc ...
type ResolverFunc func(c *fiber.Ctx, cfg Config) error
// Resolve blocks until all fragments have been called.
func (r *Resolver) Resolve(c *fiber.Ctx, cfg Config, doc *HtmlFragment) (int, []*html.Node, error) {
statusCode := fiber.StatusOK
head := make([]*html.Node, 0)
ff, err := doc.Fragments()
if err != nil {
return statusCode, head, err
}
for _, f := range ff {
r.run(c, cfg, f.Resolve())
}
r.wg.Wait()
for _, f := range ff {
if f.Primary() && f.statusCode != 0 {
statusCode = f.statusCode
}
fw, err := f.HtmlFragment().Fragments()
if err != nil {
return statusCode, head, err
}
for _, fwr := range fw {
if fwr.Ref() == "" {
continue
}
ref, ok := ff[fwr.Ref()]
if !ok {
continue
}
html, err := ref.HtmlFragment().Html()
if err != nil {
return statusCode, head, err
}
fwr.Element().ReplaceWithHtml(html)
}
html, err := f.HtmlFragment().Html()
if err != nil {
return statusCode, head, err
}
f.Element().ReplaceWithHtml(html)
head = append(head, f.Links()...)
}
return statusCode, head, nil
}
func (r *Resolver) run(c *fiber.Ctx, cfg Config, fn ResolverFunc) {
r.wg.Add(1)
go func() {
defer r.wg.Done()
err := fn(c, cfg)
if err != nil {
return // ignoring errors for now
}
}()
}