-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.go
More file actions
30 lines (28 loc) · 820 Bytes
/
middleware.go
File metadata and controls
30 lines (28 loc) · 820 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package restruct
import (
"fmt"
"log/slog"
"net/http"
"runtime/debug"
)
// Recovery middleware handles panics and returns 500 error
func Recovery(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
slog.Error("panic recovered", "error", err, "stack", string(debug.Stack()))
er := Error{
Status: http.StatusInternalServerError,
Message: fmt.Sprintf("Internal Server Error: %v", err),
}
if r.Header.Get("Content-Type") == "application/json" {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(fmt.Sprintf(`{"error": "%s"}`, er.Message)))
} else {
http.Error(w, er.Error(), http.StatusInternalServerError)
}
}
}()
next.ServeHTTP(w, r)
})
}