-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplate.go
79 lines (63 loc) · 1.45 KB
/
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
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
75
76
77
78
79
package notifybot
import (
"bytes"
"fmt"
"strings"
"text/template"
)
const (
slash = "/"
com = "."
)
type Templater interface {
Do(date interface{}) (string, error)
}
type templates struct {
templates map[string]*template.Template
content map[string]string
asset assetFunc
assetName assetNameFunc
}
type assetFunc func(name string) ([]byte, error)
type assetNameFunc func() []string
func buildTemplates(asset assetFunc, assetName assetNameFunc) (Templater, error) {
t := &templates{
templates: make(map[string]*template.Template),
content: make(map[string]string),
asset: asset,
assetName: assetName,
}
names := t.assetName()
for _, name := range names {
b, err := t.asset(name)
if err != nil {
return nil, err
}
i := strings.Index(name, slash)
j := strings.Index(name, com)
service := name[i+1 : j]
temple, err := template.New(service).Parse(string(b))
if err != nil {
return nil, err
}
t.templates[service] = temple
t.content[name] = string(b)
}
return t, nil
}
func (t *templates) Do(data interface{}) (string, error) {
if stringer, ok := data.(fmt.Stringer); ok {
name := stringer.String()
buff := &bytes.Buffer{}
temple, ok := t.templates[name]
if !ok {
return "", fmt.Errorf("template %s not found", name)
}
err := temple.Execute(buff, data)
if err != nil {
return "", err
}
return buff.String(), nil
}
return "", fmt.Errorf("data %v not implement fmt.Stringer", data)
}