go
22 lines · 1 tab
Leah Thompson
Jan 2026
1 tab
package middleware
import (
"net/http"
"go.uber.org/zap"
)
func Recover(log *zap.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if v := recover(); v != nil {
log.Error("panic.recovered", zap.Any("panic", v), zap.String("path", r.URL.Path))
http.Error(w, "internal server error", http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
}
}
1 file · go
Explain with highlit
Even in Go, panics happen: a nil pointer in an edge case, a bad slice index, or a library bug. I don't want a single request to take down the whole process, so I wrap handlers with a recovery middleware that captures panics, logs them with request context, and returns a safe 500. The important detail is to keep the response body generic (don't leak internals) while still capturing enough debug information in logs. I also attach a request_id header so a customer report can be tied to a specific failure. This middleware is not a replacement for tests, but it turns catastrophic crashes into contained errors and buys you time to ship a fix without burning a whole deploy.
Related snips
go
package api
import (
"net/http"
"runtime/debug"
)
Expose build metadata for debugging deploys
go
observability
build
by Leah Thompson
1 tab
typescript
export interface RetryOptions {
retries: number;
baseMs: number;
maxMs: number;
signal?: AbortSignal;
onRetry?: (attempt: number, delay: number, err: unknown) => void;
Exponential backoff with jitter for retries
typescript
reliability
retry
by codesnips
2 tabs
go
package dbutil
import (
"context"
"github.com/jackc/pgconn"
Retry Postgres serialization failures with bounded attempts
go
postgres
transactions
by Leah Thompson
1 tab
go
package files
import (
"context"
"time"
Presigned S3 upload URLs (AWS SDK v2)
go
aws
s3
by Leah Thompson
1 tab
go
package deps
import (
"net"
"net/http"
"time"
HTTP client tuned for production: timeouts, transport, and connection reuse
go
http
client
by Leah Thompson
1 tab
go
package api
import (
"io"
"net/http"
"os"
Safe multipart uploads using temp files (bounded memory)
go
http
uploads
by Leah Thompson
1 tab
Share this code
Here's the card — post it anywhere.