forked from leominov/prometheus-actions
-
Notifications
You must be signed in to change notification settings - Fork 3
/
template.go
93 lines (78 loc) · 1.81 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package main
import (
"bytes"
"fmt"
"net/url"
"reflect"
"strings"
"text/template"
)
var TemplateFuncMap = template.FuncMap{
"replace": func(s1 string, s2 string) string {
defer recovery()
return strings.Replace(s2, s1, "", -1)
},
"default": func(arg interface{}, value interface{}) interface{} {
defer recovery()
v := reflect.ValueOf(value)
switch v.Kind() {
case reflect.String, reflect.Slice, reflect.Array, reflect.Map:
if v.Len() == 0 {
return arg
}
case reflect.Bool:
if !v.Bool() {
return arg
}
}
return value
},
"length": func(value interface{}) int {
defer recovery()
v := reflect.ValueOf(value)
switch v.Kind() {
case reflect.Slice, reflect.Array, reflect.Map:
return v.Len()
case reflect.String:
return len([]rune(v.String()))
}
return 0
},
"lower": func(s string) string {
defer recovery()
return strings.ToLower(s)
},
"upper": func(s string) string {
defer recovery()
return strings.ToUpper(s)
},
"urlencode": func(s string) string {
defer recovery()
return url.QueryEscape(s)
},
"trim": func(s string) string {
defer recovery()
return strings.TrimSpace(s)
},
"yesno": func(yes string, no string, value bool) string {
defer recovery()
if value {
return yes
}
return no
},
}
func recovery() {
recover()
}
func GenerateTemplate(templ, name string, data interface{}) (string, error) {
var templateEng *template.Template
buf := bytes.NewBufferString("")
templateEng = template.New(name)
if messageTempl, err := templateEng.Funcs(TemplateFuncMap).Parse(templ); err != nil {
return "", fmt.Errorf("failed to parse template for %s: %v", name, err)
} else if err := messageTempl.Execute(buf, data); err != nil {
return "", fmt.Errorf("failed to execute template for %s: %v", name, err)
}
return buf.String(), nil
}