Commit 56728e65 authored by Mitchell Hashimoto's avatar Mitchell Hashimoto

common: support user data

parent 53d0095c
...@@ -2,25 +2,29 @@ package common ...@@ -2,25 +2,29 @@ package common
import ( import (
"bytes" "bytes"
"fmt"
"strconv" "strconv"
"text/template" "text/template"
"time" "time"
) )
type Template struct { type Template struct {
UserData map[string]string
root *template.Template root *template.Template
} }
func NewTemplate() (*Template, error) { func NewTemplate() (*Template, error) {
root := template.New("configTemplateRoot")
root.Funcs(template.FuncMap{
"timestamp": templateTimestamp,
})
result := &Template{ result := &Template{
root: root, UserData: make(map[string]string),
} }
result.root = template.New("configTemplateRoot")
result.root.Funcs(template.FuncMap{
"timestamp": templateTimestamp,
"user": result.templateUser,
})
return result, nil return result, nil
} }
...@@ -38,6 +42,17 @@ func (t *Template) Process(s string, data interface{}) (string, error) { ...@@ -38,6 +42,17 @@ func (t *Template) Process(s string, data interface{}) (string, error) {
return buf.String(), nil return buf.String(), nil
} }
// User is the function exposed as "user" within the templates and
// looks up user variables.
func (t *Template) templateUser(n string) (string, error) {
result, ok := t.UserData[n]
if !ok {
return "", fmt.Errorf("uknown user var: %s", n)
}
return result, nil
}
func templateTimestamp() string { func templateTimestamp() string {
return strconv.FormatInt(time.Now().UTC().Unix(), 10) return strconv.FormatInt(time.Now().UTC().Unix(), 10)
} }
...@@ -7,7 +7,7 @@ import ( ...@@ -7,7 +7,7 @@ import (
"time" "time"
) )
func TestTemplateProcess(t *testing.T) { func TestTemplateProcess_timestamp(t *testing.T) {
tpl, err := NewTemplate() tpl, err := NewTemplate()
if err != nil { if err != nil {
t.Fatalf("err: %s", err) t.Fatalf("err: %s", err)
...@@ -28,3 +28,21 @@ func TestTemplateProcess(t *testing.T) { ...@@ -28,3 +28,21 @@ func TestTemplateProcess(t *testing.T) {
t.Fatalf("val: %d (current: %d)", val, currentTime) t.Fatalf("val: %d (current: %d)", val, currentTime)
} }
} }
func TestTemplateProcess_user(t *testing.T) {
tpl, err := NewTemplate()
if err != nil {
t.Fatalf("err: %s", err)
}
tpl.UserData["foo"] = "bar"
result, err := tpl.Process(`{{user "foo"}}`, nil)
if err != nil {
t.Fatalf("err: %s", err)
}
if result != "bar" {
t.Fatalf("bad: %s", result)
}
}
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