From 53d0095cb2a0c4a6d163ef5f21411746e271a721 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Thu, 8 Aug 2013 14:00:01 -0700 Subject: [PATCH] common: functions for template processing --- common/template.go | 43 +++++++++++++++++++++++++++++++++++++++++ common/template_test.go | 30 ++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 common/template.go create mode 100644 common/template_test.go diff --git a/common/template.go b/common/template.go new file mode 100644 index 000000000..66adb3de8 --- /dev/null +++ b/common/template.go @@ -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) +} diff --git a/common/template_test.go b/common/template_test.go new file mode 100644 index 000000000..6161f3429 --- /dev/null +++ b/common/template_test.go @@ -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) + } +}