ソースを参照

Disable HTML escaping for JSON in formatter

Signed-off-by: Boaz Shuster <ripcurld.github@gmail.com>
Boaz Shuster 8 年 前
コミット
5766317e33
2 ファイル変更18 行追加2 行削除
  1. 7 2
      pkg/templates/templates.go
  2. 11 0
      pkg/templates/templates_test.go

+ 7 - 2
pkg/templates/templates.go

@@ -1,6 +1,7 @@
 package templates
 package templates
 
 
 import (
 import (
+	"bytes"
 	"encoding/json"
 	"encoding/json"
 	"strings"
 	"strings"
 	"text/template"
 	"text/template"
@@ -10,8 +11,12 @@ import (
 // functions provided to every template.
 // functions provided to every template.
 var basicFunctions = template.FuncMap{
 var basicFunctions = template.FuncMap{
 	"json": func(v interface{}) string {
 	"json": func(v interface{}) string {
-		a, _ := json.Marshal(v)
-		return string(a)
+		buf := &bytes.Buffer{}
+		enc := json.NewEncoder(buf)
+		enc.SetEscapeHTML(false)
+		enc.Encode(v)
+		// Remove the trailing new line added by the encoder
+		return strings.TrimSpace(buf.String())
 	},
 	},
 	"split":    strings.Split,
 	"split":    strings.Split,
 	"join":     strings.Join,
 	"join":     strings.Join,

+ 11 - 0
pkg/templates/templates_test.go

@@ -7,6 +7,17 @@ import (
 	"github.com/stretchr/testify/assert"
 	"github.com/stretchr/testify/assert"
 )
 )
 
 
+// Github #32120
+func TestParseJSONFunctions(t *testing.T) {
+	tm, err := Parse(`{{json .Ports}}`)
+	assert.NoError(t, err)
+
+	var b bytes.Buffer
+	assert.NoError(t, tm.Execute(&b, map[string]string{"Ports": "0.0.0.0:2->8/udp"}))
+	want := "\"0.0.0.0:2->8/udp\""
+	assert.Equal(t, want, b.String())
+}
+
 func TestParseStringFunctions(t *testing.T) {
 func TestParseStringFunctions(t *testing.T) {
 	tm, err := Parse(`{{join (split . ":") "/"}}`)
 	tm, err := Parse(`{{join (split . ":") "/"}}`)
 	assert.NoError(t, err)
 	assert.NoError(t, err)