From ecd598ab645b56264ab9f29270a02e9fe6d759ca Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Thu, 8 Aug 2013 14:05:05 -0700 Subject: [PATCH] common: support user data --- common/template.go | 27 +++++++++++++++++++++------ common/template_test.go | 20 +++++++++++++++++++- 2 files changed, 40 insertions(+), 7 deletions(-) diff --git a/common/template.go b/common/template.go index 66adb3de8..c78628092 100644 --- a/common/template.go +++ b/common/template.go @@ -2,25 +2,29 @@ package common import ( "bytes" + "fmt" "strconv" "text/template" "time" ) type Template struct { + UserData map[string]string + root *template.Template } func NewTemplate() (*Template, error) { - root := template.New("configTemplateRoot") - root.Funcs(template.FuncMap{ - "timestamp": templateTimestamp, - }) - 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 } @@ -38,6 +42,17 @@ func (t *Template) Process(s string, data interface{}) (string, error) { 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 { return strconv.FormatInt(time.Now().UTC().Unix(), 10) } diff --git a/common/template_test.go b/common/template_test.go index 6161f3429..4b59bfeb3 100644 --- a/common/template_test.go +++ b/common/template_test.go @@ -7,7 +7,7 @@ import ( "time" ) -func TestTemplateProcess(t *testing.T) { +func TestTemplateProcess_timestamp(t *testing.T) { tpl, err := NewTemplate() if err != nil { t.Fatalf("err: %s", err) @@ -28,3 +28,21 @@ func TestTemplateProcess(t *testing.T) { 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) + } +}