@@ -15,6 +15,7 @@ import (
1515"strings"
1616"testing"
1717
18+ "github.com/gin-gonic/gin/internal/json"
1819testdata "github.com/gin-gonic/gin/testdata/protoexample"
1920"github.com/stretchr/testify/assert"
2021"google.golang.org/protobuf/proto"
@@ -136,6 +137,51 @@ func TestRenderJsonpJSON(t *testing.T) {
136137assert .Equal (t , "application/javascript; charset=utf-8" , w2 .Header ().Get ("Content-Type" ))
137138}
138139
140+ type errorWriter struct {
141+ bufString string
142+ * httptest.ResponseRecorder
143+ }
144+
145+ var _ http.ResponseWriter = (* errorWriter )(nil )
146+
147+ func (w * errorWriter ) Write (buf []byte ) (int , error ) {
148+ if string (buf ) == w .bufString {
149+ return 0 , errors .New (`write "` + w .bufString + `" error` )
150+ }
151+ return w .ResponseRecorder .Write (buf )
152+ }
153+
154+ func TestRenderJsonpJSONError (t * testing.T ) {
155+ ew := & errorWriter {
156+ ResponseRecorder : httptest .NewRecorder (),
157+ }
158+
159+ jsonpJSON := JsonpJSON {
160+ Callback : "foo" ,
161+ Data : map [string ]string {
162+ "foo" : "bar" ,
163+ },
164+ }
165+
166+ cb := template .JSEscapeString (jsonpJSON .Callback )
167+ ew .bufString = cb
168+ err := jsonpJSON .Render (ew ) // error was returned while writing callback
169+ assert .Equal (t , `write "` + cb + `" error` , err .Error ())
170+
171+ ew .bufString = `(`
172+ err = jsonpJSON .Render (ew )
173+ assert .Equal (t , `write "` + `(` + `" error` , err .Error ())
174+
175+ data , _ := json .Marshal (jsonpJSON .Data ) // error was returned while writing data
176+ ew .bufString = string (data )
177+ err = jsonpJSON .Render (ew )
178+ assert .Equal (t , `write "` + string (data )+ `" error` , err .Error ())
179+
180+ ew .bufString = `);`
181+ err = jsonpJSON .Render (ew )
182+ assert .Equal (t , `write "` + `);` + `" error` , err .Error ())
183+ }
184+
139185func TestRenderJsonpJSONError2 (t * testing.T ) {
140186w := httptest .NewRecorder ()
141187data := map [string ]any {
0 commit comments