forked from saiya/dsps
-
Notifications
You must be signed in to change notification settings - Fork 2
/
datatype_template_string.go
67 lines (57 loc) · 1.61 KB
/
datatype_template_string.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
package domain
import (
"encoding/json"
"strings"
"text/template"
"golang.org/x/xerrors"
)
// TemplateString is Template wrappwer struct
type TemplateString struct {
template *template.Template
templateString string
}
// TemplateStringEnv is an parameters for template evaluation
type TemplateStringEnv interface{}
// NewTemplateString initialize template
func NewTemplateString(value string) (TemplateString, error) {
result := TemplateString{}
return result, result.init(value)
}
func (tpl *TemplateString) init(value string) error {
parsed, err := template.New("template-string").Option("missingkey=error").Parse(value)
if err != nil {
return xerrors.Errorf("Unable to parse Template \"%s\" %w", value, err)
}
tpl.template = parsed
tpl.templateString = value
return nil
}
// String returns original template string
func (tpl TemplateString) String() string {
return tpl.templateString
}
// Execute evaluates template
func (tpl TemplateString) Execute(data TemplateStringEnv) (string, error) {
output := strings.Builder{}
if err := tpl.template.Execute(&output, data); err != nil {
return "", err
}
return output.String(), nil
}
// MarshalJSON method for configuration marshal/unmarshal
func (tpl TemplateString) MarshalJSON() ([]byte, error) {
return json.Marshal(tpl.templateString)
}
// UnmarshalJSON method for configuration marshal/unmarshal
func (tpl *TemplateString) UnmarshalJSON(b []byte) error {
var v interface{}
if err := json.Unmarshal(b, &v); err != nil {
return err
}
switch value := v.(type) {
case string:
return tpl.init(value)
default:
return xerrors.New("invalid template")
}
}