Files
tyapi-server/internal/infrastructure/http/handlers/pdfg_handler.go

97 lines
2.4 KiB
Go
Raw Normal View History

2026-01-27 16:26:48 +08:00
package handlers
import (
"fmt"
"net/http"
2026-01-29 15:48:07 +08:00
"strings"
2026-01-27 16:26:48 +08:00
"time"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"tyapi-server/internal/shared/interfaces"
"tyapi-server/internal/shared/pdf"
)
// PDFGHandler PDFG处理器
type PDFGHandler struct {
cacheManager *pdf.PDFCacheManager
responseBuilder interfaces.ResponseBuilder
logger *zap.Logger
}
// NewPDFGHandler 创建PDFG处理器
func NewPDFGHandler(
cacheManager *pdf.PDFCacheManager,
responseBuilder interfaces.ResponseBuilder,
logger *zap.Logger,
) *PDFGHandler {
return &PDFGHandler{
cacheManager: cacheManager,
responseBuilder: responseBuilder,
logger: logger,
}
}
// DownloadPDF 下载PDF文件
2026-01-29 15:03:38 +08:00
// GET /api/v1/pdfg/download?id=报告ID
2026-01-27 16:26:48 +08:00
func (h *PDFGHandler) DownloadPDF(c *gin.Context) {
2026-01-29 16:34:37 +08:00
reportID := c.Query("id")
2026-01-27 16:26:48 +08:00
2026-01-29 16:34:37 +08:00
if reportID == "" {
2026-01-29 15:03:38 +08:00
h.responseBuilder.BadRequest(c, "报告ID不能为空")
2026-01-27 16:26:48 +08:00
return
}
2026-01-29 16:34:37 +08:00
// 通过报告ID获取PDF文件
pdfBytes, hit, createdAt, err := h.cacheManager.GetByReportID(reportID)
2026-01-27 16:26:48 +08:00
if err != nil {
h.logger.Error("获取PDF缓存失败",
2026-01-29 16:34:37 +08:00
zap.String("report_id", reportID),
2026-01-27 16:26:48 +08:00
zap.Error(err),
)
h.responseBuilder.InternalError(c, "获取PDF文件失败")
return
}
if !hit {
h.logger.Warn("PDF文件不存在或已过期",
2026-01-29 16:34:37 +08:00
zap.String("report_id", reportID),
2026-01-27 16:26:48 +08:00
)
h.responseBuilder.NotFound(c, "PDF文件不存在或已过期请重新生成")
return
}
// 检查是否过期从文件生成时间开始算24小时
expiresAt := createdAt.Add(24 * time.Hour)
if time.Now().After(expiresAt) {
h.logger.Warn("PDF文件已过期",
2026-01-29 16:34:37 +08:00
zap.String("report_id", reportID),
2026-01-27 16:26:48 +08:00
zap.Time("expires_at", expiresAt),
)
h.responseBuilder.NotFound(c, "PDF文件已过期请重新生成")
return
}
// 设置响应头
c.Header("Content-Type", "application/pdf")
2026-01-29 16:34:37 +08:00
// 使用报告ID前缀作为下载文件名的一部分
2026-01-29 15:48:07 +08:00
filename := "大数据租赁风险报告.pdf"
2026-01-29 16:34:37 +08:00
if idx := strings.LastIndex(reportID, "-"); idx > 0 {
2026-01-29 15:48:07 +08:00
// 使用前缀(报告编号部分)作为文件名的一部分
2026-01-29 16:34:37 +08:00
prefix := reportID[:idx]
2026-01-29 15:48:07 +08:00
filename = fmt.Sprintf("大数据租赁风险报告_%s.pdf", prefix)
}
c.Header("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, filename))
2026-01-27 16:26:48 +08:00
c.Header("Content-Length", fmt.Sprintf("%d", len(pdfBytes)))
// 发送PDF文件
c.Data(http.StatusOK, "application/pdf", pdfBytes)
h.logger.Info("PDF文件下载成功",
2026-01-29 16:34:37 +08:00
zap.String("report_id", reportID),
2026-01-27 16:26:48 +08:00
zap.Int("file_size", len(pdfBytes)),
)
}