Skip to content

Commit

Permalink
add toJSON func to templates
Browse files Browse the repository at this point in the history
Signed-off-by: Justin Kolberg <amd.prophet@gmail.com>
  • Loading branch information
amdprophet committed Feb 26, 2024
1 parent 4afd7be commit fcdb550
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
13 changes: 12 additions & 1 deletion templates/templates.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ package templates

import (
"bytes"
"encoding/json"
"fmt"
"github.com/google/uuid"
"os"
"text/template"
"time"

"github.com/google/uuid"
)

func EvalTemplate(templName, templStr string, templSrc interface{}) (string, error) {
Expand All @@ -21,6 +23,7 @@ func EvalTemplate(templName, templStr string, templSrc interface{}) (string, err
"UnixTime": func(i int64) time.Time { return time.Unix(i, 0) },
"UUIDFromBytes": uuid.FromBytes,
"Hostname": os.Hostname,
"toJSON": toJSON,
}).Parse(templStr)
if err != nil {
return "", fmt.Errorf("Error building template: %s", err)
Expand All @@ -34,3 +37,11 @@ func EvalTemplate(templName, templStr string, templSrc interface{}) (string, err

return buf.String(), nil
}

func toJSON(i any) string {
b, err := json.Marshal(i)
if err != nil {
return ""
}
return string(b)
}
13 changes: 13 additions & 0 deletions templates/templates_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ var (
templateOkHostname = "Check: {{ .Check.Name }} Entity: {{ .Entity.Name }} Hostname: {{Hostname}} !"
templateVarNotFound = "Check: {{ .Check.NameZZZ }} Entity: {{ .Entity.Name }} !"
templateInvalid = "Check: {{ .Check.Name Entity: {{ .Entity.Name }} !"
templateJSON = `{"name": "{{ .Check.Name }}", "output": {{ toJSON .Check.Output }}}`
)

// Valid test
Expand Down Expand Up @@ -99,3 +100,15 @@ func TestEvalTemplate_InvalidTemplate(t *testing.T) {
assert.Equal(t, "", result)
assert.NotNil(t, err)
}

// JSON template
func TestEvalTemplate_JSONTemplate(t *testing.T) {
event := &corev2.Event{}
event.Check = &corev2.Check{}
event.Check.Name = "foo"
event.Check.Output = "foo\nbar"

result, err := EvalTemplate("templOk", templateJSON, event)
assert.Equal(t, `{"name": "foo", "output": "foo\nbar"}`, result)
assert.Nil(t, err)
}

0 comments on commit fcdb550

Please sign in to comment.