traefik/pkg/middlewares/recovery/recovery.go

58 lines
1.7 KiB
Go
Raw Normal View History

2018-11-14 09:18:03 +00:00
package recovery
import (
"context"
"net/http"
2019-10-18 09:30:05 +00:00
"runtime"
2018-11-14 09:18:03 +00:00
2023-02-03 14:24:05 +00:00
"github.com/traefik/traefik/v3/pkg/middlewares"
2018-11-14 09:18:03 +00:00
)
const (
typeName = "Recovery"
middlewareName = "traefik-internal-recovery"
2018-11-14 09:18:03 +00:00
)
type recovery struct {
next http.Handler
}
// New creates recovery middleware.
func New(ctx context.Context, next http.Handler) (http.Handler, error) {
2022-11-21 17:36:05 +00:00
middlewares.GetLogger(ctx, middlewareName, typeName).Debug().Msg("Creating middleware")
2018-11-14 09:18:03 +00:00
return &recovery{
next: next,
}, nil
}
func (re *recovery) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
defer recoverFunc(rw, req)
2018-11-14 09:18:03 +00:00
re.next.ServeHTTP(rw, req)
}
2022-11-21 17:36:05 +00:00
func recoverFunc(rw http.ResponseWriter, req *http.Request) {
2018-11-14 09:18:03 +00:00
if err := recover(); err != nil {
2022-11-21 17:36:05 +00:00
logger := middlewares.GetLogger(req.Context(), middlewareName, typeName)
2019-10-18 09:30:05 +00:00
if !shouldLogPanic(err) {
2022-11-21 17:36:05 +00:00
logger.Debug().Msgf("Request has been aborted [%s - %s]: %v", req.RemoteAddr, req.URL, err)
2019-10-18 09:30:05 +00:00
return
}
2022-11-21 17:36:05 +00:00
logger.Error().Msgf("Recovered from panic in HTTP handler [%s - %s]: %+v", req.RemoteAddr, req.URL, err)
2019-10-18 09:30:05 +00:00
const size = 64 << 10
buf := make([]byte, size)
buf = buf[:runtime.Stack(buf, false)]
2022-11-21 17:36:05 +00:00
logger.Error().Msgf("Stack: %s", buf)
2019-10-18 09:30:05 +00:00
2018-11-14 09:18:03 +00:00
http.Error(rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
}
2019-10-18 09:30:05 +00:00
// https://github.com/golang/go/blob/a0d6420d8be2ae7164797051ec74fa2a2df466a1/src/net/http/server.go#L1761-L1775
// https://github.com/golang/go/blob/c33153f7b416c03983324b3e8f869ce1116d84bc/src/net/http/httputil/reverseproxy.go#L284
func shouldLogPanic(panicValue interface{}) bool {
2020-11-06 08:26:03 +00:00
//nolint:errorlint // false-positive because panicValue is an interface.
2019-10-18 09:30:05 +00:00
return panicValue != nil && panicValue != http.ErrAbortHandler
}