-
Notifications
You must be signed in to change notification settings - Fork 6
/
utils.go
69 lines (59 loc) · 1.18 KB
/
utils.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
package htmlgo
import (
"bytes"
"context"
"fmt"
"html"
"io"
)
type RawHTML string
func (s RawHTML) MarshalHTML(ctx context.Context) (r []byte, err error) {
r = []byte(s)
return
}
func Text(text string) (r HTMLComponent) {
return RawHTML(html.EscapeString(text))
}
func Textf(format string, a ...interface{}) (r HTMLComponent) {
return Text(fmt.Sprintf(format, a...))
}
type HTMLComponents []HTMLComponent
func Components(comps ...HTMLComponent) HTMLComponents {
return HTMLComponents(comps)
}
func (hcs HTMLComponents) MarshalHTML(ctx context.Context) (r []byte, err error) {
buf := bytes.NewBuffer(nil)
for _, h := range hcs {
if h == nil {
continue
}
var b []byte
b, err = h.MarshalHTML(ctx)
if err != nil {
return
}
buf.Write(b)
}
r = buf.Bytes()
return
}
func Fprint(w io.Writer, root HTMLComponent, ctx context.Context) (err error) {
if root == nil {
return
}
var b []byte
b, err = root.MarshalHTML(ctx)
if err != nil {
return
}
_, err = fmt.Fprint(w, string(b))
return
}
func MustString(root HTMLComponent, ctx context.Context) string {
b := bytes.NewBuffer(nil)
err := Fprint(b, root, ctx)
if err != nil {
panic(err)
}
return b.String()
}