package middleware import ( "fmt" "log/slog" "net" "net/http" "net/http/httputil" "os" "runtime/debug" "strings" "kra/internal/service" "kra/internal/service/dto" "github.com/gin-gonic/gin" ) func Recovery(audit *service.AuditRecorder, logger *slog.Logger) gin.HandlerFunc { return func(c *gin.Context) { defer func() { panicValue := recover() if panicValue == nil { return } brokenPipe := false if networkError, ok := panicValue.(*net.OpError); ok { if syscallError, ok := networkError.Err.(*os.SyscallError); ok { message := strings.ToLower(syscallError.Error()) brokenPipe = strings.Contains(message, "broken pipe") || strings.Contains(message, "connection reset by peer") } } request, _ := httputil.DumpRequest(c.Request, false) info := fmt.Sprintf("error=%v request=%s stack=%s", panicValue, request, debug.Stack()) if logger != nil { logger.ErrorContext(c.Request.Context(), "recovery from panic", "error", panicValue, "request", string(request), "stack", string(debug.Stack())) } requestID, _ := c.Get("request_id") _ = audit.CreateErrorRequest(c.Request.Context(), &dto.ErrorRecordRequest{Form: c.Request.URL.Path, Info: info, Level: "error", RequestID: stringValue(requestID), TraceID: stringValueFromContext(c, "trace_id"), Status: "未解决"}) if brokenPipe { if err, ok := panicValue.(error); ok { _ = c.Error(err) } c.Abort() return } c.AbortWithStatus(http.StatusInternalServerError) }() c.Next() } }