Created
August 27, 2024 19:59
-
-
Save dlisboa/bb9d6f813e905d94173c0bcb73fce350 to your computer and use it in GitHub Desktop.
Recover go middleware
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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