-
Notifications
You must be signed in to change notification settings - Fork 0
/
strslot_renderer.go
63 lines (57 loc) · 1.7 KB
/
strslot_renderer.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
package structemplate
import (
"encoding/json"
"github.com/drone/envsubst/v2"
"github.com/pkg/errors"
)
// RenderStrSlotTemplate Rendering a string template containing StrSlot params with the values map.
// @Param tmpl The template string
// @Param valuesMapOfInterface (optional) values of parameters
// @Param valuesMapOfString (optional) value of parameters
// @Return result Rendered string result
// @Return missingKeys missing keys that defined in the template without default value and no value is provided
// @Return err Other errors
func RenderStrSlotTemplate(tmpl string, valuesMapOfInterface map[string]interface{}, valuesMapOfString map[string]string) (result string, missingKeys []string, err error) {
envTmpl, err := envsubst.Parse(tmpl)
if err != nil {
return "", nil, errors.Wrap(err, "cannot parse the template")
}
if valuesMapOfInterface == nil {
valuesMapOfInterface = make(map[string]interface{}, 0)
}
if valuesMapOfString == nil {
valuesMapOfString = make(map[string]string, 0)
}
var missingParams []string
execFunc := func(key string) string {
v, iok := valuesMapOfInterface[key]
vs, sok := valuesMapOfString[key]
if !sok && !iok {
// missing param
missingParams = append(missingParams, key)
return ""
}
var valueStr string
if sok {
valueStr = vs
} else {
switch v := v.(type) {
case string:
valueStr = v
default:
valueB, err := json.Marshal(v)
if err != nil {
missingParams = append(missingParams, key)
return ""
}
valueStr = string(valueB)
}
}
return valueStr
}
result, err = envTmpl.Execute(execFunc)
if err != nil {
return "", nil, errors.Wrap(err, "cannot render the template")
}
return result, missingKeys, nil
}