This repository has been archived by the owner on Aug 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
template.go
73 lines (60 loc) · 1.71 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"text/template"
"time"
)
func templateDatetime() string {
timeNow := time.Now()
return timeNow.Format("2006-01-02-15:04:05")
}
// register custom go template functions
func registerTemplateFunctions() template.FuncMap {
return template.FuncMap{
"datetime": templateDatetime,
}
}
// render template
func generateTemplate(templatePath string, values map[string]interface{}) (string, error) {
var renderedTemplate string
templateFileContent, err := ioutil.ReadFile(templatePath)
if err != nil {
return renderedTemplate, err
}
templateFunctions := registerTemplateFunctions()
templateRender, err := template.New("template").Funcs(templateFunctions).Parse(string(templateFileContent))
if err != nil {
return renderedTemplate, err
}
templateRederBuffer := &bytes.Buffer{}
err = templateRender.Execute(templateRederBuffer, values)
if err != nil {
return renderedTemplate, err
}
renderedTemplate = templateRederBuffer.String()
return renderedTemplate, nil
}
// render template or return plain secrets text
func renderOutput(secretsString, templatePath string) (string, error) {
var secretsMap map[string]interface{}
var secretsOutput string
var err error
secretsOutput = secretsString
// try to convert json secrets to map interfaces or return plan secret value
err = json.Unmarshal([]byte(secretsString), &secretsMap)
if err != nil {
return secretsOutput, nil
}
// render secrets as template
if templatePath != "" {
secretsOutput, err = generateTemplate(templatePath, secretsMap)
if err != nil {
return secretsOutput, fmt.Errorf("failed to render secrets template - %s", err)
}
}
// return plain json
return secretsOutput, nil
}