From f34fc61a9a579c6a6fc634838361e073dbe9ee54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Mon, 25 Jul 2022 13:10:44 +0200 Subject: [PATCH] api: avoid HTML-escaping JSON output json.Marshal does HTML-escaping by default, which is what we don't want since we're printing to the terminal instead of embedding this JSON into a HTML document. --- pkg/jsoncolor/jsoncolor.go | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/pkg/jsoncolor/jsoncolor.go b/pkg/jsoncolor/jsoncolor.go index d7c808a14..dbe3d9a4b 100644 --- a/pkg/jsoncolor/jsoncolor.go +++ b/pkg/jsoncolor/jsoncolor.go @@ -1,6 +1,7 @@ package jsoncolor import ( + "bytes" "encoding/json" "fmt" "io" @@ -49,7 +50,7 @@ func Write(w io.Writer, r io.Reader, indent string) error { fmt.Fprintf(w, "\x1b[%sm%s\x1b[m", colorDelim, tt) } default: - b, err := json.Marshal(tt) + b, err := marshalJSON(tt) if err != nil { return err } @@ -94,3 +95,19 @@ func Write(w io.Writer, r io.Reader, indent string) error { return nil } + +// marshalJSON works like json.Marshal but with HTML-escaping disabled +func marshalJSON(v interface{}) ([]byte, error) { + buf := bytes.Buffer{} + enc := json.NewEncoder(&buf) + enc.SetEscapeHTML(false) + if err := enc.Encode(v); err != nil { + return nil, err + } + bb := buf.Bytes() + // omit trailing newline added by json.Encoder + if len(bb) > 0 && bb[len(bb)-1] == '\n' { + return bb[:len(bb)-1], nil + } + return bb, nil +}