diff --git a/templates/templates.go b/templates/templates.go index 830a9e7..9f9d7f7 100644 --- a/templates/templates.go +++ b/templates/templates.go @@ -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) { @@ -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) @@ -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) +} diff --git a/templates/templates_test.go b/templates/templates_test.go index 3bb9f53..8842d4d 100644 --- a/templates/templates_test.go +++ b/templates/templates_test.go @@ -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 @@ -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) +}