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

Stop useless panicking in context and render #2150

Merged
merged 16 commits into from Feb 12, 2023
Merged
Show file tree
Hide file tree
Changes from 12 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
3 changes: 2 additions & 1 deletion context.go
Expand Up @@ -843,7 +843,8 @@ func (c *Context) Render(code int, r render.Render) {
}

if err := r.Render(c.Writer); err != nil {
panic(err)
c.Error(err)
c.Abort()
}
}

Expand Down
12 changes: 5 additions & 7 deletions context_test.go
Expand Up @@ -31,6 +31,8 @@ import (

var _ context.Context = &Context{}

var errTestPanicRender = errors.New("TestPanicRender")

// Unit tests TODO
// func (c *Context) File(filepath string) {
// func (c *Context) Negotiate(code int, config Negotiate) {
Expand Down Expand Up @@ -636,22 +638,18 @@ type TestPanicRender struct {
}

func (*TestPanicRender) Render(http.ResponseWriter) error {
return errors.New("TestPanicRender")
return errTestPanicRender
}

func (*TestPanicRender) WriteContentType(http.ResponseWriter) {}

func TestContextRenderPanicIfErr(t *testing.T) {
defer func() {
r := recover()
assert.Equal(t, "TestPanicRender", fmt.Sprint(r))
}()
func TestContextRenderIfErr(t *testing.T) {
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)

c.Render(http.StatusOK, &TestPanicRender{})

assert.Fail(t, "Panic not detected")
assert.Equal(t, errorMsgs{&Error{Err: errTestPanicRender, Type: 1}}, c.Errors)
}

// Tests that the response is serialized as JSON
Expand Down
6 changes: 2 additions & 4 deletions render/json.go
Expand Up @@ -52,10 +52,8 @@ var jsonAsciiContentType = []string{"application/json"}

// 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
r.WriteContentType(w)
return json.NewEncoder(w).Encode(r.Data)
}

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

func TestRenderJSONPanics(t *testing.T) {
func TestRenderJSONError(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))
}

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