-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplate.go
40 lines (35 loc) · 883 Bytes
/
template.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
package main
import (
"bytes"
"errors"
"fmt"
"path"
"text/template"
"github.com/yosssi/gohtml"
)
type TemplateMaker struct {
inputPath string
}
func (t *TemplateMaker) Execute(data any) ([]byte, error) {
var rdbuf bytes.Buffer
err := t.getTemplate().Execute(&rdbuf, data)
if err != nil {
return make([]byte, 0), fmt.Errorf("executing tmpl: %v", err)
}
out := make([]byte, rdbuf.Len())
br, err := rdbuf.Read(out)
if err != nil {
return make([]byte, 0), fmt.Errorf("reading tmpl: %v, bytes read: %d", err, br)
}
return gohtml.FormatBytes(out), nil
}
func (t *TemplateMaker) getTemplate() *template.Template {
if !path.IsAbs(t.inputPath) {
panic(errors.New(fmt.Sprintf("invalid path %v", t.inputPath)))
}
tmpl, err := template.ParseFiles(t.inputPath)
if err != nil {
panic(errors.New(fmt.Sprintf("failed to parse template %v", tmpl)))
}
return tmpl
}