Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't panic when failed to render or write JSON #3390

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 1 addition & 4 deletions render/json.go
Expand Up @@ -54,10 +54,7 @@ var (

// Render (JSON) writes data with custom ContentType.
func (r JSON) Render(w http.ResponseWriter) (err error) {
if err = WriteJSON(w, r.Data); err != nil {
panic(err)
}
return
return WriteJSON(w, r.Data)
}

// WriteContentType (JSON) writes JSON ContentType.
Expand Down
22 changes: 20 additions & 2 deletions render/render_test.go
Expand Up @@ -39,12 +39,30 @@ func TestRenderJSON(t *testing.T) {
assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
}

func TestRenderJSONPanics(t *testing.T) {
func TestRenderJSONFail(t *testing.T) {
w := httptest.NewRecorder()
data := make(chan int)

// json: unsupported type: chan int
assert.Panics(t, func() { assert.NoError(t, (JSON{data}).Render(w)) })
assert.Error(t, (JSON{data}).Render(w))
}

type mockWriter struct {
*httptest.ResponseRecorder
}

func (mock *mockWriter) Write(buf []byte) (int, error) {
return 0, errors.New("mock write error")
}

func TestRenderJSONWriteFail(t *testing.T) {
w := &mockWriter{
ResponseRecorder: httptest.NewRecorder(),
}
err := (JSON{map[string]any{
"foo": "bar",
}}).Render(w)
assert.Equal(t, errors.New("mock write error"), err)
}

func TestRenderIndentedJSON(t *testing.T) {
Expand Down