Skip to content

Commit

Permalink
feat: support templating struct fields of type []byte
Browse files Browse the repository at this point in the history
  • Loading branch information
adityathebe authored and moshloop committed Oct 22, 2024
1 parent af3f8dd commit 7c2cb02
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
10 changes: 10 additions & 0 deletions structtemplater.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,16 @@ func (w StructTemplater) StructField(f reflect.StructField, v reflect.Value) err
}
v.SetString(val)

case reflect.Slice:
switch v.Type().Elem().Kind() {
case reflect.Uint8:
val, err := w.Template(string(v.Bytes()))
if err != nil {
return err
}
v.SetBytes([]byte(val))
}

case reflect.Map:
if len(v.MapKeys()) != 0 {
newMap := reflect.MakeMap(v.Type())
Expand Down
28 changes: 25 additions & 3 deletions structtemplater_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package gomplate

import (
"encoding/json"
"testing"

"github.com/google/go-cmp/cmp"
Expand All @@ -10,6 +11,7 @@ type Test struct {
Template string `template:"true"`
NoTemplate string
Inner Inner
Properties json.RawMessage `template:"true"`
JSONMap map[string]any `template:"true"`
Labels map[string]string `template:"true"`
LabelsRaw map[string]string
Expand All @@ -28,6 +30,21 @@ type test struct {
}

var tests = []test{
{
name: "template byte slice",
StructTemplater: StructTemplater{
RequiredTag: "template",
Values: map[string]any{
"msg": "world",
},
},
Input: &Test{
Properties: json.RawMessage(`{"name": "{{.msg}}"}`),
},
Output: &Test{
Properties: json.RawMessage(`{"name": "world"}`),
},
},
{
name: "template and no template",
StructTemplater: StructTemplater{
Expand All @@ -43,6 +60,7 @@ var tests = []test{
Output: &Test{
Template: "hello world",
NoTemplate: "hello {{.msg}}",
Properties: json.RawMessage{},
},
},
{
Expand All @@ -61,7 +79,8 @@ var tests = []test{
Template: "hello $(msg)",
},
Output: &Test{
Template: "hello world",
Template: "hello world",
Properties: json.RawMessage{},
},
},
{
Expand Down Expand Up @@ -96,7 +115,8 @@ var tests = []test{
},
},
Output: &Test{
Template: "Special Agent - James Bond!",
Template: "Special Agent - James Bond!",
Properties: json.RawMessage{},
Labels: map[string]string{
"address": "London, UK",
"eye color": "light blue",
Expand Down Expand Up @@ -135,7 +155,8 @@ var tests = []test{
},
},
Output: &Test{
Template: "world",
Template: "world",
Properties: json.RawMessage{},
JSONMap: map[string]any{
"a": map[string]any{
"b": map[string]any{
Expand Down Expand Up @@ -187,6 +208,7 @@ var tests = []test{
},
},
Output: &Test{
Properties: json.RawMessage{},
JSONMap: map[string]any{
"apiVersion": "v1",
"kind": "Pod",
Expand Down

0 comments on commit 7c2cb02

Please sign in to comment.