mirror of
https://github.com/gin-gonic/gin.git
synced 2026-11-23 11:33:37 +08:00
fix(render): encode non-BMP runes as UTF-16 surrogate pairs in AsciiJSON
AsciiJSON escaped every non-ASCII rune with \u%04x, but %04x is a minimum width — for code points above U+FFFF it produced 5+ hex digits, creating a malformed \uXXXXX escape. JSON \u escapes must be exactly 4 hex digits; non-BMP characters must be encoded as UTF-16 surrogate pairs per RFC 8259 §7. For example, U+1F600 (😀) was emitted as \u1f600 (which decodes to U+1F60 + literal '0') instead of \ud83d\ude00. Fixes #4688
This commit is contained in:
parent
34dac209ff
commit
e89c60b4e4
@ -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))
|
||||
}
|
||||
|
||||
@ -5,6 +5,7 @@
|
||||
package render
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"html/template"
|
||||
@ -269,6 +270,22 @@ 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)
|
||||
|
||||
// Non-BMP characters must be encoded as UTF-16 surrogate pairs
|
||||
assert.Equal(t, `{"msg":"\ud83d\ude00"}`, w.Body.String())
|
||||
|
||||
// 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{
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user