packer-cn/common/template.go

59 lines
1.1 KiB
Go
Raw Normal View History

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