/
template_builder.go
74 lines (64 loc) · 1.99 KB
/
template_builder.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
73
74
package goplate
import (
"errors"
"fmt"
"strings"
)
// TransformFunc is the transformation function for template expressions
type TransformFunc func(interface{}) []byte
// TransformFunctionMap is the function transform map for the templates.
type TransformFunctionMap map[string]TransformFunc
// Builder is an type to build and configure template instances.
type Builder struct {
TemplateString string
Transforms TransformFunctionMap
Parameters interface{}
}
// New creates a new template builder
func New(templateString string) *Builder {
ret := &Builder{
TemplateString: templateString,
Parameters: nil,
Transforms: TransformFunctionMap{
"json": DefaultJSONTransformFunc(DefaultMarshaler()),
"asTime": Int64ToDateString,
"hex": HexConversion,
},
}
return ret
}
// WithTransforms modifies the transform function map for the template. The
// transform function map is used to apply transformations to fields in the
// merged data structure. They are simple strings with no parameters and the
// key to the
func (t *Builder) WithTransforms(transformMap TransformFunctionMap) *Builder {
for k, v := range transformMap {
t.Transforms[k] = v
}
return t
}
// WithParameters sets the parameter type used for the template. When the structure
// is built it will use this parameter struct to validate the template
func (t *Builder) WithParameters(params interface{}) *Builder {
t.Parameters = params
return t
}
func (t *Builder) WithJSONMarshaler(marshaler JSONMarshaler) *Builder {
t.Transforms["json"] = DefaultJSONTransformFunc(marshaler)
return t
}
// Build builds and validates the template
func (t *Builder) Build() (*Template, error) {
if t.TemplateString == "" || t.Parameters == nil {
return nil, errors.New("missing parameters")
}
template, err := newTemplate(t.TemplateString, t.Transforms, t.Parameters)
if err != nil {
return nil, err
}
ok, errors := template.Validate()
if !ok {
return nil, fmt.Errorf(strings.Join(errors, ","))
}
return template, nil
}