2013-08-08 14:00:01 -07:00
|
|
|
package common
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2013-08-08 14:05:05 -07:00
|
|
|
"fmt"
|
2013-08-08 14:00:01 -07:00
|
|
|
"strconv"
|
|
|
|
"text/template"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Template struct {
|
2013-08-08 14:05:05 -07:00
|
|
|
UserData map[string]string
|
|
|
|
|
2013-08-08 14:00:01 -07:00
|
|
|
root *template.Template
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewTemplate() (*Template, error) {
|
|
|
|
result := &Template{
|
2013-08-08 14:05:05 -07:00
|
|
|
UserData: make(map[string]string),
|
2013-08-08 14:00:01 -07:00
|
|
|
}
|
|
|
|
|
2013-08-08 14:05:05 -07:00
|
|
|
result.root = template.New("configTemplateRoot")
|
|
|
|
result.root.Funcs(template.FuncMap{
|
|
|
|
"timestamp": templateTimestamp,
|
|
|
|
"user": result.templateUser,
|
|
|
|
})
|
|
|
|
|
2013-08-08 14:00:01 -07:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2013-08-08 14:05:05 -07:00
|
|
|
// 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
|
|
|
|
}
|
|
|
|
|
2013-08-08 14:00:01 -07:00
|
|
|
func templateTimestamp() string {
|
|
|
|
return strconv.FormatInt(time.Now().UTC().Unix(), 10)
|
|
|
|
}
|