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

Recover correctly after writing #81

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion recovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"log"
"net/http"
"net/http/httptest"
"os"
"runtime"
)
Expand All @@ -27,6 +28,9 @@ func NewRecovery() *Recovery {
}

func (rec *Recovery) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
nr := httptest.NewRecorder()
nrw := NewResponseWriter(nr)

defer func() {
if err := recover(); err != nil {
rw.WriteHeader(http.StatusInternalServerError)
Expand All @@ -39,8 +43,14 @@ func (rec *Recovery) ServeHTTP(rw http.ResponseWriter, r *http.Request, next htt
if rec.PrintStack {
fmt.Fprintf(rw, f, err, stack)
}
} else {
for k, v := range nrw.Header() {
rw.Header()[k] = v
}
rw.WriteHeader(nr.Code)
rw.Write(nr.Body.Bytes())
}
}()

next(rw, r)
next(nrw, r)
}
39 changes: 39 additions & 0 deletions recovery_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,25 @@ import (
"testing"
)

func TestNoRecovery(t *testing.T) {
buff := bytes.NewBufferString("")
recorder := httptest.NewRecorder()

rec := NewRecovery()
rec.Logger = log.New(buff, "[negroni] ", 0)

n := New()
// replace log for testing
n.Use(rec)
n.UseHandler(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
fmt.Fprint(res, "writing")
}))
n.ServeHTTP(recorder, (*http.Request)(nil))
expect(t, recorder.Code, http.StatusOK)
refute(t, recorder.Body.Len(), 0)
expect(t, len(buff.String()), 0)
}

func TestRecovery(t *testing.T) {
buff := bytes.NewBufferString("")
recorder := httptest.NewRecorder()
Expand All @@ -26,3 +45,23 @@ func TestRecovery(t *testing.T) {
refute(t, recorder.Body.Len(), 0)
refute(t, len(buff.String()), 0)
}

func TestRecoveryAfterWriting(t *testing.T) {
buff := bytes.NewBufferString("")
recorder := httptest.NewRecorder()

rec := NewRecovery()
rec.Logger = log.New(buff, "[negroni] ", 0)

n := New()
// replace log for testing
n.Use(rec)
n.UseHandler(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
fmt.Fprint(res, "writing")
panic("here is a panic!")
}))
n.ServeHTTP(recorder, (*http.Request)(nil))
expect(t, recorder.Code, http.StatusInternalServerError)
refute(t, recorder.Body.Len(), 0)
refute(t, len(buff.String()), 0)
}