@@ -4,25 +4,65 @@ import (
4
4
"bytes"
5
5
_ "embed"
6
6
"io"
7
- "strings"
8
7
)
9
8
10
9
//go:embed html_default_page.html
11
- var DefaultHTMLPageTemplate string
10
+ var defaultPageTemplate [] byte
12
11
13
- func MarshalHTML (v any ) []byte {
12
+ var DefaultPageMarshaler = PageMarshaler {
13
+ Title : "htmljson" ,
14
+ Template : defaultPageTemplate ,
15
+ TemplateTitleKey : `{{.Title}}` ,
16
+ TemplateJSONKey : `{{.HTMLJSON}}` ,
17
+ Marshaler : & DefaultMarshaler ,
18
+ }
19
+
20
+ // PageMarshaler encodes JSON via marshaller into HTML page by placing Title and content appropriately.
21
+ type PageMarshaler struct {
22
+ Title string
23
+ Template []byte
24
+ TemplateTitleKey string
25
+ TemplateJSONKey string
26
+
27
+ Marshaler interface {
28
+ MarshalTo (w io.Writer , v any ) error
29
+ }
30
+
31
+ idxTitle int
32
+ idxHTMLJSON int
33
+ }
34
+
35
+ func (m * PageMarshaler ) Marshal (v any ) []byte {
14
36
b := bytes.Buffer {}
15
- MarshalHTMLTo (& b , v )
37
+ m . MarshalTo (& b , v )
16
38
return b .Bytes ()
17
39
}
18
40
19
- func MarshalHTMLTo (w io.Writer , v any ) (written int64 , err error ) {
20
- var b bytes.Buffer
21
- b .Grow (1000 )
41
+ func (m * PageMarshaler ) parseTemplate () {
42
+ if m .idxTitle == 0 || m .idxHTMLJSON == 0 {
43
+ m .idxTitle = bytes .Index (m .Template , []byte (m .TemplateTitleKey ))
44
+ m .idxHTMLJSON = bytes .Index (m .Template , []byte (m .TemplateJSONKey ))
45
+ }
46
+ }
47
+
48
+ func (m * PageMarshaler ) MarshalTo (w io.Writer , v any ) error {
49
+ m .parseTemplate ()
50
+
51
+ var s int
52
+
53
+ if f := m .idxTitle ; f > 0 {
54
+ w .Write (m .Template [s :f ])
55
+ s = f + len (m .TemplateTitleKey )
56
+ w .Write ([]byte (m .Title ))
57
+ }
58
+
59
+ if f := m .idxHTMLJSON ; f > 0 {
60
+ w .Write (m .Template [s :f ])
61
+ s = f + len (m .TemplateJSONKey )
62
+ m .Marshaler .MarshalTo (w , v )
63
+ }
22
64
23
- jsonHTML := DefaultMarshaler .Marshal (v )
24
- b .WriteString (strings .ReplaceAll (DefaultHTMLPageTemplate , `{{.HTMLJSON}}` , string (jsonHTML )))
65
+ w .Write (m .Template [s :])
25
66
26
- n , err := w .Write (b .Bytes ())
27
- return int64 (n ), err
67
+ return nil
28
68
}
0 commit comments