| |
| |
| package middleware |
|
|
| import ( |
| "fmt" |
| "net/http" |
| "runtime/debug" |
|
|
| "github.com/gin-gonic/gin" |
| "github.com/sirupsen/logrus" |
|
|
| "github.com/router-for-me/CLIProxyAPI/v6/internal/application/dto" |
| ) |
|
|
| |
| |
| |
| func RecoveryMiddleware(logger *logrus.Logger) gin.HandlerFunc { |
| return func(c *gin.Context) { |
| defer func() { |
| if r := recover(); r != nil { |
| requestID := c.GetString("request_id") |
| |
| if logger != nil { |
| logger.WithFields(logrus.Fields{ |
| "panic": r, |
| "stacktrace": string(debug.Stack()), |
| "path": c.Request.URL.Path, |
| "method": c.Request.Method, |
| "client_ip": c.ClientIP(), |
| "request_id": requestID, |
| }).Error("Panic recovered in HTTP handler") |
| } |
|
|
| |
| c.AbortWithStatusJSON(http.StatusInternalServerError, dto.InternalErrorResponse{ |
| Success: false, |
| RequestID: requestID, |
| Error: "An internal server error occurred", |
| }) |
| } |
| }() |
|
|
| c.Next() |
| } |
| } |
|
|
| |
| |
| func SafeHandler(handler gin.HandlerFunc) gin.HandlerFunc { |
| return func(c *gin.Context) { |
| defer func() { |
| if r := recover(); r != nil { |
| requestID := c.GetString("request_id") |
| |
| logrus.WithFields(logrus.Fields{ |
| "panic": fmt.Sprintf("%v", r), |
| "path": c.Request.URL.Path, |
| "method": c.Request.Method, |
| "request_id": requestID, |
| }).Error("Panic recovered in handler") |
|
|
| c.AbortWithStatusJSON(http.StatusInternalServerError, dto.InternalErrorResponse{ |
| Success: false, |
| RequestID: requestID, |
| Error: "An internal server error occurred", |
| }) |
| } |
| }() |
|
|
| handler(c) |
| } |
| } |
|
|