Skip to content

Commit

Permalink
explicitly set Content-Type in Recovery handler
Browse files Browse the repository at this point in the history
writing the panic HTML content without a known content-type header
is unreliable and leads to unpredictable results - particularly when
used with other middleware that sets the header in various cases
  • Loading branch information
thevisus committed Feb 3, 2014
1 parent ec4ae4a commit 1c3ccf1
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
10 changes: 8 additions & 2 deletions recovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,13 +114,19 @@ func Recovery() Handler {
return func(res http.ResponseWriter, c Context, log *log.Logger) {
defer func() {
if err := recover(); err != nil {
res.WriteHeader(http.StatusInternalServerError)
stack := stack(3)
log.Printf("PANIC: %s\n%s", err, stack)

// respond with panic message while in development mode
var body []byte
if Env == Dev {
res.Write([]byte(fmt.Sprintf(panicHtml, err, err, stack)))
res.Header().Set("Content-Type", "text/html")
body = []byte(fmt.Sprintf(panicHtml, err, err, stack))
}

res.WriteHeader(http.StatusInternalServerError)
if nil != body {
res.Write(body)
}
}
}()
Expand Down
6 changes: 5 additions & 1 deletion recovery_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,19 @@ func Test_Recovery(t *testing.T) {
buff := bytes.NewBufferString("")
recorder := httptest.NewRecorder()

setENV(Dev)
m := New()
// replace log for testing
m.Map(log.New(buff, "[martini] ", 0))
m.Use(func(res http.ResponseWriter, req *http.Request) {
res.Header().Set("Content-Type", "unpredictable")
})
m.Use(Recovery())
m.Use(func(res http.ResponseWriter, req *http.Request) {
panic("here is a panic!")
})
m.ServeHTTP(recorder, (*http.Request)(nil))
expect(t, recorder.Code, http.StatusInternalServerError)
expect(t, recorder.HeaderMap.Get("Content-Type"), "text/html")
refute(t, len(buff.String()), 0)

}

0 comments on commit 1c3ccf1

Please sign in to comment.