-
Notifications
You must be signed in to change notification settings - Fork 36
/
template.go
51 lines (38 loc) · 1.11 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
package template
import (
"bytes"
"strings"
"text/template"
"github.com/adohe/kube2haproxy/proxy"
)
type TemplateData struct {
IPs map[string]bool
RouteTable map[string]*proxy.ServiceUnit
}
func hasIP(ipsMap map[string]bool, ip string) bool {
return ipsMap[ip]
}
// Returns string content of a rendered template
func RenderTemplate(templateName, templateContent string, data interface{}) ([]byte, error) {
tpl := template.Must(template.New(templateName).Parse(templateContent))
strBuffer := new(bytes.Buffer)
err := tpl.Execute(strBuffer, data)
if err != nil {
return nil, err
}
return strBuffer.Bytes(), nil
}
// Returns string content of a rendered template (with template functions)
func RenderTemplateWithFuncs(templateName, templateContent string, data interface{}) ([]byte, error) {
funcMap := template.FuncMap{
"hasIP": hasIP,
"ToLower": strings.ToLower,
}
tpl := template.Must(template.New(templateName).Funcs(funcMap).Parse(templateContent))
strBuffer := new(bytes.Buffer)
err := tpl.Execute(strBuffer, data)
if err != nil {
return nil, err
}
return strBuffer.Bytes(), nil
}