Files
coder/httpmw/recover.go
T
Spike Curtis bddb808b25 chore: arrange imports in a standard way (#21452)
Fixes all our Go file imports to match the preferred spec that we've _mostly_ been using. For example:

```
import (
	"context"
	"time"

	"github.com/prometheus/client_golang/prometheus"
	"golang.org/x/xerrors"
	"gopkg.in/natefinch/lumberjack.v2"

	"cdr.dev/slog/v3"
	"github.com/coder/coder/v2/codersdk/agentsdk"
	"github.com/coder/serpent"
)
```

3 groups: standard library, 3rd partly libs, Coder libs.

This PR makes the change across the codebase. The PR in the stack above modifies our formatting to maintain this state of affairs, and is a separate PR so it's possible to review that one in detail.
2026-01-08 15:24:11 +04:00

48 lines
1.1 KiB
Go

package httpmw
import (
"context"
"net/http"
"runtime/debug"
"cdr.dev/slog/v3"
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/coderd/tracing"
)
func Recover(log slog.Logger) func(h http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
r := recover()
// Reverse proxying (among other things) may panic with
// http.ErrAbortHandler when the request is aborted. It's not a
// real panic so we shouldn't log them.
//
//nolint:errorlint // this is how the stdlib does the check
if r != nil && r != http.ErrAbortHandler {
log.Warn(context.Background(),
"panic serving http request (recovered)",
slog.F("panic", r),
slog.F("stack", string(debug.Stack())),
)
var hijacked bool
if sw, ok := w.(*tracing.StatusWriter); ok {
hijacked = sw.Hijacked
}
// Only try to write errors on
// non-hijacked responses.
if !hijacked {
httpapi.InternalServerError(w, nil)
}
}
}()
h.ServeHTTP(w, r)
})
}
}