traefik/pkg/middlewares/recovery/recovery.go

41 lines
987 B
Go
Raw Normal View History

2018-11-14 09:18:03 +00:00
package recovery
import (
"context"
"net/http"
2019-09-13 17:28:04 +00:00
"github.com/containous/traefik/v2/pkg/log"
2019-08-03 01:58:23 +00:00
"github.com/containous/traefik/v2/pkg/middlewares"
2018-11-14 09:18:03 +00:00
)
const (
typeName = "Recovery"
)
type recovery struct {
next http.Handler
name string
}
// New creates recovery middleware.
func New(ctx context.Context, next http.Handler, name string) (http.Handler, error) {
2019-09-13 17:28:04 +00:00
log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware")
2018-11-14 09:18:03 +00:00
return &recovery{
next: next,
name: name,
}, nil
}
func (re *recovery) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
2019-09-13 17:28:04 +00:00
defer recoverFunc(middlewares.GetLoggerCtx(req.Context(), re.name, typeName), rw)
2018-11-14 09:18:03 +00:00
re.next.ServeHTTP(rw, req)
}
2019-09-13 17:28:04 +00:00
func recoverFunc(ctx context.Context, rw http.ResponseWriter) {
2018-11-14 09:18:03 +00:00
if err := recover(); err != nil {
2019-09-13 17:28:04 +00:00
log.FromContext(ctx).Errorf("Recovered from panic in http handler: %+v", err)
2018-11-14 09:18:03 +00:00
http.Error(rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
}