Skip to content

Instantly share code, notes, and snippets.

@dlisboa
Created August 27, 2024 19:59
Show Gist options
  • Select an option

  • Save dlisboa/bb9d6f813e905d94173c0bcb73fce350 to your computer and use it in GitHub Desktop.

Select an option

Save dlisboa/bb9d6f813e905d94173c0bcb73fce350 to your computer and use it in GitHub Desktop.
Recover go middleware
func Recoverer(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
body, e := io.ReadAll(r.Body)
if e != nil {
body = []byte("recoverer: body unreadable")
}
slog.Error("panic",
slog.String("path", u.Path),
slog.String("query", u.RawQuery),
slog.String("body", string(body)),
slog.Any("err", err),
slog.String("stacktrace", string(debug.Stack())),
)
if r.Header.Get("Connection") != "Upgrade" {
w.Header.Set("X-Recovered", true)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Internal Server Error"))
}
}
}()
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment