Merge d0c2793becbd2f065b1a4942fb346b09fb855a37 into dcaa4296d111981ffb31ac3eba90bb63e1eb5ab9

This commit is contained in:
Md Mushfiqur Rahim 2026-08-19 23:09:58 -07:00 committed by GitHub
commit 90982d0e1e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 20 additions and 2 deletions

View File

@ -1306,6 +1306,18 @@ func TestContextRenderNoContentSecureJSON(t *testing.T) {
assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
}
func TestContextAsciiJSONNonBMP(t *testing.T) {
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)
// Non-BMP characters (emoji) should be encoded as UTF-16 surrogate pairs
c.AsciiJSON(http.StatusOK, H{"emoji": "😀"})
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, "{\"emoji\":\"\\ud83d\\ude00\"}", w.Body.String())
assert.Equal(t, "application/json", w.Header().Get("Content-Type"))
}
func TestContextRenderNoContentAsciiJSON(t *testing.T) {
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)

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"
@ -160,11 +161,16 @@ func (r AsciiJSON) Render(w http.ResponseWriter) error {
}
var buffer bytes.Buffer
escapeBuf := make([]byte, 0, 6) // Preallocate 6 bytes for Unicode escape sequences
escapeBuf := make([]byte, 0, 12) // Preallocate for up to two \uXXXX sequences
for _, r := range bytesconv.BytesToString(ret) {
if r > unicode.MaxASCII {
escapeBuf = fmt.Appendf(escapeBuf[:0], "\\u%04x", r) // Reuse escapeBuf
if r > 0xFFFF {
surrogates := utf16.Encode([]rune{r})
escapeBuf = fmt.Appendf(escapeBuf[:0], "\\u%04x\\u%04x", surrogates[0], surrogates[1])
} else {
escapeBuf = fmt.Appendf(escapeBuf[:0], "\\u%04x", r)
}
buffer.Write(escapeBuf)
} else {
buffer.WriteByte(byte(r))