-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.go
72 lines (59 loc) · 1.03 KB
/
script.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
package carbon
import (
_ "embed"
"io"
"net/http"
)
var _scriptCache map[string]string
func init() {
// initialize script cache
_scriptCache = make(map[string]string)
}
var _ Component = (*script)(nil)
type script struct {
attr []Attr
script string
}
func Script(s string) *script {
s, _ = _m.String("text/javascript", s)
return &script{
attr: nil,
script: s,
}
}
func InlineScript(href string) *script {
if s, ok := _scriptCache[href]; ok {
return &script{
attr: nil,
script: s,
}
}
r, err := http.Get(href)
if err != nil {
panic(err)
}
defer r.Body.Close()
b, err := io.ReadAll(r.Body)
if err != nil {
panic(err)
}
s := string(b)
_scriptCache[href] = s
return &script{
attr: nil,
script: s,
}
}
func (s *script) Attr(name string, value string) *script {
s.attr = append(s.attr, Attr{name, value})
return s
}
func (s *script) Render(w io.Writer) {
w.Write([]byte(`<script`))
renderAttrs(w, s.attr)
w.Write([]byte(`>`))
{
io.WriteString(w, s.script)
}
w.Write([]byte(`</script>`))
}