Merge 09303fb04e679fbe73f22953d382c50e5d6bb15f into 3b08cd7235bd5ad2f055aa9e38135f111f6c5926

This commit is contained in:
Ruben Pari 2026-09-20 13:08:36 +00:00 committed by GitHub
commit 8d8e1c561c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 28 additions and 2 deletions

View File

@ -10,6 +10,7 @@ import (
"html/template"
"net/http"
"unicode"
"unicode/utf16"
"github.com/gin-gonic/gin/codec/json"
"github.com/gin-gonic/gin/internal/bytesconv"
@ -164,8 +165,14 @@ func (r AsciiJSON) Render(w http.ResponseWriter) error {
for _, r := range bytesconv.BytesToString(ret) {
if r > unicode.MaxASCII {
escapeBuf = fmt.Appendf(escapeBuf[:0], "\\u%04x", r) // Reuse escapeBuf
buffer.Write(escapeBuf)
if r <= 0xFFFF {
escapeBuf = fmt.Appendf(escapeBuf[:0], "\\u%04x", r)
buffer.Write(escapeBuf)
} else {
r1, r2 := utf16.EncodeRune(r)
escapeBuf = fmt.Appendf(escapeBuf[:0], "\\u%04x\\u%04x", r1, r2)
buffer.Write(escapeBuf)
}
} else {
buffer.WriteByte(byte(r))
}

View File

@ -5,6 +5,7 @@
package render
import (
"encoding/json"
"encoding/xml"
"errors"
"html/template"
@ -269,6 +270,24 @@ func TestRenderAsciiJSONFail(t *testing.T) {
require.Error(t, (AsciiJSON{data}).Render(w))
}
func TestRenderAsciiJSONNonBMP(t *testing.T) {
w := httptest.NewRecorder()
data := map[string]string{"msg": "😀"}
err := (AsciiJSON{Data: data}).Render(w)
require.NoError(t, err)
body := w.Body.String()
// Non-BMP characters must be encoded as UTF-16 surrogate pairs on the wire.
assert.Contains(t, body, `\ud83d\ude00`)
assert.JSONEq(t, `{"msg":"😀"}`, body)
// Verify round-trip: json.Unmarshal should recover the original emoji
var decoded map[string]string
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &decoded))
assert.Equal(t, "😀", decoded["msg"])
}
func TestRenderPureJSON(t *testing.T) {
w := httptest.NewRecorder()
data := map[string]any{