-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
html_default_page.go
68 lines (54 loc) · 1.37 KB
/
html_default_page.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
package htmljson
import (
"bytes"
_ "embed"
"io"
)
//go:embed html_default_page.html
var defaultPageTemplate []byte
var DefaultPageMarshaler = PageMarshaler{
Title: "htmljson",
Template: defaultPageTemplate,
TemplateTitleKey: `{{.Title}}`,
TemplateJSONKey: `{{.HTMLJSON}}`,
Marshaler: &DefaultMarshaler,
}
// PageMarshaler encodes JSON via marshaller into HTML page by placing Title and content appropriately.
type PageMarshaler struct {
Title string
Template []byte
TemplateTitleKey string
TemplateJSONKey string
Marshaler interface {
MarshalTo(w io.Writer, v any) error
}
idxTitle int
idxHTMLJSON int
}
func (m *PageMarshaler) Marshal(v any) []byte {
b := bytes.Buffer{}
m.MarshalTo(&b, v)
return b.Bytes()
}
func (m *PageMarshaler) parseTemplate() {
if m.idxTitle == 0 || m.idxHTMLJSON == 0 {
m.idxTitle = bytes.Index(m.Template, []byte(m.TemplateTitleKey))
m.idxHTMLJSON = bytes.Index(m.Template, []byte(m.TemplateJSONKey))
}
}
func (m *PageMarshaler) MarshalTo(w io.Writer, v any) error {
m.parseTemplate()
var s int
if f := m.idxTitle; f > 0 {
w.Write(m.Template[s:f])
s = f + len(m.TemplateTitleKey)
w.Write([]byte(m.Title))
}
if f := m.idxHTMLJSON; f > 0 {
w.Write(m.Template[s:f])
s = f + len(m.TemplateJSONKey)
m.Marshaler.MarshalTo(w, v)
}
w.Write(m.Template[s:])
return nil
}