- add Formatter.JSONEscapeHTML and SetJSONEscapeHTML to let JSON writers preserve HTML-sensitive characters when needed while keeping escaping enabled by default. - switch JSON output to json.Encoder, preserve existing Print/Println newline semantics, and cover the new escaping behavior in tests.
This commit is contained in:
@@ -342,6 +342,42 @@ func TestJsonWriterPrintAllowsEmptyMessages(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestJsonWriterPrintDoesNotAppendNewline(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
writer := CreateJsonWriter(&buf, false)
|
||||
|
||||
if err := writer.Print(INFO, "TEST", nil, "hello"); err != nil {
|
||||
t.Fatalf("Print() error = %v", err)
|
||||
}
|
||||
|
||||
if bytes.HasSuffix(buf.Bytes(), []byte("\n")) {
|
||||
t.Fatalf("Print() should not append newline, got %q", buf.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestJsonWriterSetJSONEscapeHTML(t *testing.T) {
|
||||
var escaped bytes.Buffer
|
||||
escapedWriter := CreateJsonWriter(&escaped, false)
|
||||
|
||||
if err := escapedWriter.Print(INFO, "TEST", nil, "<>&"); err != nil {
|
||||
t.Fatalf("Print() with default formatter error = %v", err)
|
||||
}
|
||||
if strings.Contains(escaped.String(), "<>&") {
|
||||
t.Fatalf("default JSON output should escape HTML-sensitive characters, got %q", escaped.String())
|
||||
}
|
||||
|
||||
var raw bytes.Buffer
|
||||
rawWriter := CreateJsonWriter(&raw, false).
|
||||
SetFormatter(NewFormatter().SetFormat("%m").SetJSONEscapeHTML(false))
|
||||
|
||||
if err := rawWriter.Print(INFO, "TEST", nil, "<>&"); err != nil {
|
||||
t.Fatalf("Print() with SetJSONEscapeHTML(false) error = %v", err)
|
||||
}
|
||||
if !strings.Contains(raw.String(), "<>&") {
|
||||
t.Fatalf("SetJSONEscapeHTML(false) should preserve HTML-sensitive characters, got %q", raw.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestJsonWriterPrintPreservesTrailingNewlineSemantic(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
writer := CreateJsonWriter(&buf, false)
|
||||
@@ -354,6 +390,9 @@ func TestJsonWriterPrintPreservesTrailingNewlineSemantic(t *testing.T) {
|
||||
if !bytes.HasSuffix(data, []byte("\n")) {
|
||||
t.Fatalf("JSON output should end with newline, got %q", data)
|
||||
}
|
||||
if bytes.HasSuffix(bytes.TrimSuffix(data, []byte("\n")), []byte("\n")) {
|
||||
t.Fatalf("JSON output should end with exactly one newline, got %q", data)
|
||||
}
|
||||
|
||||
var message LoggerJsonMessage
|
||||
if err := json.Unmarshal(bytes.TrimSuffix(data, []byte("\n")), &message); err != nil {
|
||||
|
||||
Reference in New Issue
Block a user