|
3 | 3 | package utils
|
4 | 4 |
|
5 | 5 | import (
|
| 6 | + "net/http/httptest" |
| 7 | + "reflect" |
| 8 | + "strings" |
6 | 9 | "testing"
|
7 | 10 | )
|
8 | 11 |
|
@@ -53,3 +56,54 @@ func TestErrorEncoderFuncOmit(t *testing.T) {
|
53 | 56 | t.Errorf("the `errs` field shouldn't have been omitted")
|
54 | 57 | }
|
55 | 58 | }
|
| 59 | + |
| 60 | +func TestWriteJSONNoHTMLEscape(t *testing.T) { |
| 61 | + // Test that WriteJSON does not HTML-escape JSON content |
| 62 | + // This test verifies the fix for issue #17769 |
| 63 | + |
| 64 | + recorder := httptest.NewRecorder() |
| 65 | + |
| 66 | + // Test data with characters that would be HTML-escaped |
| 67 | + testData := map[string]string{ |
| 68 | + "message": "Hello <world> & \"friends\"", |
| 69 | + "script": "<script>alert('test')</script>", |
| 70 | + "url": "https://example.com/path?param=value&other=<test>", |
| 71 | + } |
| 72 | + |
| 73 | + WriteJSON(recorder, 200, testData) |
| 74 | + |
| 75 | + // Check response headers |
| 76 | + if contentType := recorder.Header().Get("Content-Type"); contentType != "application/json" { |
| 77 | + t.Errorf("Expected Content-Type 'application/json', got '%s'", contentType) |
| 78 | + } |
| 79 | + |
| 80 | + // Check that response contains unescaped characters |
| 81 | + body := recorder.Body.String() |
| 82 | + |
| 83 | + // These characters should NOT be HTML-escaped in JSON responses |
| 84 | + // (but quotes are still properly JSON-escaped) |
| 85 | + expectedUnescaped := []string{ |
| 86 | + "<world>", |
| 87 | + "&", |
| 88 | + "\\\"friends\\\"", // JSON-escaped quotes, not HTML-escaped |
| 89 | + "<script>", |
| 90 | + "<test>", |
| 91 | + } |
| 92 | + |
| 93 | + for _, expected := range expectedUnescaped { |
| 94 | + if !strings.Contains(body, expected) { |
| 95 | + t.Errorf("Expected unescaped string '%s' in response body, got: %s", expected, body) |
| 96 | + } |
| 97 | + } |
| 98 | + |
| 99 | + // Verify we can parse the JSON back |
| 100 | + var parsed map[string]string |
| 101 | + if err := json.Unmarshal([]byte(body), &parsed); err != nil { |
| 102 | + t.Errorf("Failed to parse JSON response: %v", err) |
| 103 | + } |
| 104 | + |
| 105 | + // Verify the data matches what we sent |
| 106 | + if !reflect.DeepEqual(parsed, testData) { |
| 107 | + t.Errorf("Parsed message doesn't match original: got %v, want %v", parsed, testData) |
| 108 | + } |
| 109 | +} |
0 commit comments