common: functions for template processing

This commit is contained in:
Mitchell Hashimoto 2013-08-08 14:00:01 -07:00
parent d5fb4d5570
commit 53d0095cb2
2 changed files with 73 additions and 0 deletions

43
common/template.go Normal file
View File

@ -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)
}

30
common/template_test.go Normal file
View File

@ -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)
}
}