traefik/old/middlewares/recover.go

52 lines
1.5 KiB
Go
Raw Normal View History

package middlewares
import (
2017-05-13 17:36:37 +00:00
"net/http"
2018-10-12 13:40:03 +00:00
"runtime"
2017-05-13 17:36:37 +00:00
2018-11-14 09:18:03 +00:00
"github.com/containous/traefik/old/log"
"github.com/urfave/negroni"
)
// RecoverHandler recovers from a panic in http handlers
func RecoverHandler(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
2018-10-12 13:40:03 +00:00
defer recoverFunc(w, r)
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
// NegroniRecoverHandler recovers from a panic in negroni handlers
func NegroniRecoverHandler() negroni.Handler {
fn := func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
2018-10-12 13:40:03 +00:00
defer recoverFunc(w, r)
next.ServeHTTP(w, r)
}
return negroni.HandlerFunc(fn)
}
2018-10-12 13:40:03 +00:00
func recoverFunc(w http.ResponseWriter, r *http.Request) {
if err := recover(); err != nil {
2018-10-12 13:40:03 +00:00
if !shouldLogPanic(err) {
log.Debugf("Request has been aborted [%s - %s]: %v", r.RemoteAddr, r.URL, err)
return
2018-10-12 11:04:02 +00:00
}
2018-10-12 13:40:03 +00:00
log.Errorf("Recovered from panic in HTTP handler [%s - %s]: %+v", r.RemoteAddr, r.URL, err)
const size = 64 << 10
buf := make([]byte, size)
buf = buf[:runtime.Stack(buf, false)]
log.Errorf("Stack: %s", buf)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
}
2018-10-12 11:04:02 +00:00
2018-10-12 13:40:03 +00:00
// https://github.com/golang/go/blob/a0d6420d8be2ae7164797051ec74fa2a2df466a1/src/net/http/server.go#L1761-L1775
2018-10-12 11:04:02 +00:00
// https://github.com/golang/go/blob/c33153f7b416c03983324b3e8f869ce1116d84bc/src/net/http/httputil/reverseproxy.go#L284
func shouldLogPanic(panicValue interface{}) bool {
return panicValue != nil && panicValue != http.ErrAbortHandler
}