Files
lincodex/backend/internal/adapter/primary/http/problem/recover.go
T

99 lines
2.9 KiB
Go

package problem
import (
"bufio"
"errors"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"runtime/debug"
"github.com/felixge/httpsnoop"
kitmiddleware "github.com/wahrwelt-kit/go-httpkit/httputil/middleware"
"lincodex/backend/internal/adapter/primary/http/api"
)
// Recover answers a panic in next with the internal problem response and logs
// the panic type and stack once. It must run inside the request ID middleware so the problem
// and the log entry carry the request ID. When next has already started the
// response, the status is committed and no second body is written. A panic
// with http.ErrAbortHandler is re-raised so net/http aborts the response as
// that sentinel requires.
func (responder *Responder) Recover(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tracked, started := trackResponseStart(w)
defer responder.recoverPanic(w, r, started)
next.ServeHTTP(tracked, r)
})
}
// recoverPanic must be deferred directly so that recover stops the panic.
func (responder *Responder) recoverPanic(w http.ResponseWriter, r *http.Request, started *bool) {
recovered := recover()
if recovered == nil {
return
}
if err, ok := recovered.(error); ok && errors.Is(err, http.ErrAbortHandler) {
panic(recovered)
}
ctx := r.Context()
responder.logger.ErrorContext(ctx, "public API request panicked",
slog.String("request_id", kitmiddleware.GetRequestID(ctx)),
// The panic value may hold request data, so only its type is logged.
slog.String("panic_type", fmt.Sprintf("%T", recovered)),
slog.String("stack", string(debug.Stack())),
slog.Bool("response_started", *started),
)
if !*started {
Write(w, New(ctx, api.ProblemCodeInternal))
}
}
// trackResponseStart wraps w, keeping its optional interfaces, and reports
// whether the handler has started the response.
func trackResponseStart(w http.ResponseWriter) (http.ResponseWriter, *bool) {
started := new(bool)
tracked := httpsnoop.Wrap(w, httpsnoop.Hooks{
WriteHeader: func(next httpsnoop.WriteHeaderFunc) httpsnoop.WriteHeaderFunc {
return func(code int) {
*started = true
next(code)
}
},
Write: func(next httpsnoop.WriteFunc) httpsnoop.WriteFunc {
return func(body []byte) (int, error) {
*started = true
return next(body)
}
},
WriteString: func(next httpsnoop.WriteStringFunc) httpsnoop.WriteStringFunc {
return func(body string) (int, error) {
*started = true
return next(body)
}
},
ReadFrom: func(next httpsnoop.ReadFromFunc) httpsnoop.ReadFromFunc {
return func(source io.Reader) (int64, error) {
*started = true
return next(source)
}
},
Flush: func(next httpsnoop.FlushFunc) httpsnoop.FlushFunc {
return func() {
*started = true
next()
}
},
Hijack: func(next httpsnoop.HijackFunc) httpsnoop.HijackFunc {
return func() (net.Conn, *bufio.ReadWriter, error) {
*started = true
return next()
}
},
})
return tracked, started
}