common: functions for template processing

pull/919/head
Mitchell Hashimoto 13 years ago
parent d5fb4d5570
commit 53d0095cb2

@ -0,0 +1,43 @@
package common
import (
"bytes"
"strconv"
"text/template"
"time"
)
type Template struct {
root *template.Template
}
func NewTemplate() (*Template, error) {
root := template.New("configTemplateRoot")
root.Funcs(template.FuncMap{
"timestamp": templateTimestamp,
})
result := &Template{
root: root,
}
return result, nil
}
func (t *Template) Process(s string, data interface{}) (string, error) {
tpl, err := t.root.New("tpl").Parse(s)
if err != nil {
return "", err
}
buf := new(bytes.Buffer)
if err := tpl.Execute(buf, data); err != nil {
return "", err
}
return buf.String(), nil
}
func templateTimestamp() string {
return strconv.FormatInt(time.Now().UTC().Unix(), 10)
}

@ -0,0 +1,30 @@
package common
import (
"math"
"strconv"
"testing"
"time"
)
func TestTemplateProcess(t *testing.T) {
tpl, err := NewTemplate()
if err != nil {
t.Fatalf("err: %s", err)
}
result, err := tpl.Process(`{{timestamp}}`, nil)
if err != nil {
t.Fatalf("err: %s", err)
}
val, err := strconv.ParseInt(result, 10, 64)
if err != nil {
t.Fatalf("err: %s", err)
}
currentTime := time.Now().UTC().Unix()
if math.Abs(float64(currentTime-val)) > 10 {
t.Fatalf("val: %d (current: %d)", val, currentTime)
}
}
Loading…
Cancel
Save