From ba2a101a137a9604381b66a3e1c86813cbef57ab Mon Sep 17 00:00:00 2001 From: Bennett Payoyo <75754746+Yahiro025@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:56:34 +0800 Subject: [PATCH] fix: defer the JSONP response until the serializer writes `Context.JSONP` wrote the status code, content type and callback prefix before calling the JSON serializer, so a serializer that failed left the client with a partial `callback(` body and a status the error handler could no longer change. `Context.JSON` already delays the status through `delayedStatusWriter` for the same reason. Write the prefix and the JSONP headers from the first serialized byte instead, so a serializer that fails before writing leaves the response uncommitted. Output for successful responses is unchanged. --- context.go | 26 +++++++++++++++----------- context_test.go | 13 +++++++++++++ response.go | 28 ++++++++++++++++++++++++++++ 3 files changed, 56 insertions(+), 11 deletions(-) diff --git a/context.go b/context.go index 9be52f0aa..e1cf03e40 100644 --- a/context.go +++ b/context.go @@ -573,21 +573,25 @@ func (c *Context) writeJSONPHeader(code int, callback string) error { } func (c *Context) jsonPBlob(code int, callback string, i any) (err error) { - if err = c.writeJSONPHeader(code, callback); err != nil { - return - } - if _, err = c.response.Write(stringToBytes(callback)); err != nil { - return - } - if _, err = c.response.Write(jsonpOpen); err != nil { - return + if !isValidJSONPCallback(callback) { + return ErrBadRequest.Wrap(ErrInvalidJSONPCallback) } + + // As with json(), hold the status code and headers back until the serializer writes its first + // byte, so a serializer that fails before writing anything sends no response and the error + // handler can send its own. + resp := c.Response() + c.SetResponse(&jsonpWriter{ + ResponseWriter: &delayedStatusWriter{ResponseWriter: resp, status: code}, + contentType: MIMEApplicationJavaScriptCharsetUTF8, + prefix: []byte(callback + string(jsonpOpen)), + }) + defer c.SetResponse(resp) + if err = c.echo.JSONSerializer.Serialize(c, i, ""); err != nil { return } - if _, err = c.response.Write(jsonpClose); err != nil { - return - } + _, err = c.response.Write(jsonpClose) return } diff --git a/context_test.go b/context_test.go index 9b2b59e99..dfe5f45e0 100644 --- a/context_test.go +++ b/context_test.go @@ -247,6 +247,19 @@ func TestContextJSONErrorsOut(t *testing.T) { assert.Empty(t, rec.Body.String()) // body must not be sent to the client } +func TestContextJSONPErrorsOut(t *testing.T) { + e := New() + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/", nil) + c := e.NewContext(req, rec) + + err := c.JSONP(http.StatusAccepted, "callback", make(chan bool)) + assert.EqualError(t, err, "json: unsupported type: chan bool") + + assert.Equal(t, http.StatusOK, rec.Code) // status code must not be sent to the client + assert.Empty(t, rec.Body.String()) // body must not be sent to the client +} + func TestContextJSONWithNotEchoResponse(t *testing.T) { e := New() rec := httptest.NewRecorder() diff --git a/response.go b/response.go index e6adea77c..0a3663dd7 100644 --- a/response.go +++ b/response.go @@ -225,6 +225,34 @@ func (w *delayedStatusWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } +// jsonpWriter writes the JSONP callback prefix ahead of the first serialized byte, so a serializer +// that fails before writing leaves the status code uncommitted for the error handler. +type jsonpWriter struct { + http.ResponseWriter + contentType string + prefix []byte + wrote bool +} + +func (w *jsonpWriter) Write(data []byte) (int, error) { + if !w.wrote { + w.wrote = true + header := w.ResponseWriter.Header() + if header.Get(HeaderContentType) == "" { + header.Set(HeaderContentType, w.contentType) + } + header.Set(HeaderXContentTypeOptions, "nosniff") + if _, err := w.ResponseWriter.Write(w.prefix); err != nil { + return 0, err + } + } + return w.ResponseWriter.Write(data) +} + +func (w *jsonpWriter) Unwrap() http.ResponseWriter { + return w.ResponseWriter +} + // headResponseWriter captures the response that a GET handler would produce for a // rewritten HEAD request, suppresses the body, and preserves response metadata. //