Commit 53d0095c authored by Mitchell Hashimoto's avatar Mitchell Hashimoto

common: functions for template processing

parent d5fb4d55
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)
}
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)
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment