common: support user data
This commit is contained in:
parent
915f9b73be
commit
ecd598ab64
|
@ -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)
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue