-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtemplate.go
55 lines (46 loc) · 1.08 KB
/
template.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package template
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"text/template"
)
// NewTemplate returns a new template instance
func NewTemplate() *Template {
return &Template{}
}
// Template is responsible for producing files from the given files
type Template struct{}
// ExecuteFile executes the given template file and returns the final result
func (t *Template) ExecuteFile(file string) (string, error) {
f, err := ioutil.ReadFile(file)
if err != nil {
return "", err
}
return t.Execute(string(f))
}
// Execute executes the given template and returns the final result
func (t *Template) Execute(in string) (string, error) {
funcMap := template.FuncMap{
"env": func(key string) (string, error) {
val, found := os.LookupEnv(key)
if !found {
return "", fmt.Errorf("environment variable %q is not defined", key)
}
return val, nil
},
}
tmpl, err := template.New("file").
Funcs(funcMap).
Parse(string(in))
if err != nil {
return "", err
}
var buf bytes.Buffer
err = tmpl.Execute(&buf, nil)
if err != nil {
return "", err
}
return buf.String(), nil
}