This commit is contained in:
2026-01-29 16:34:37 +08:00
parent f50e11a052
commit 5bff33547c
3 changed files with 51 additions and 32 deletions

View File

@@ -36,25 +36,18 @@ func NewPDFGHandler(
// DownloadPDF 下载PDF文件
// GET /api/v1/pdfg/download?id=报告ID
func (h *PDFGHandler) DownloadPDF(c *gin.Context) {
rawReportID := c.Query("id")
reportID := c.Query("id")
if rawReportID == "" {
if reportID == "" {
h.responseBuilder.BadRequest(c, "报告ID不能为空")
return
}
// 从对外报告ID中解析内部缓存键(使用最后一个'-'后的部分作为缓存键)
cacheKey := rawReportID
if idx := strings.LastIndex(rawReportID, "-"); idx > 0 && idx < len(rawReportID)-1 {
cacheKey = rawReportID[idx+1:]
}
// 从缓存获取PDF
pdfBytes, hit, createdAt, err := h.cacheManager.GetByCacheKey(cacheKey)
// 通过报告ID获取PDF文件
pdfBytes, hit, createdAt, err := h.cacheManager.GetByReportID(reportID)
if err != nil {
h.logger.Error("获取PDF缓存失败",
zap.String("report_id", rawReportID),
zap.String("cache_key", cacheKey),
zap.String("report_id", reportID),
zap.Error(err),
)
h.responseBuilder.InternalError(c, "获取PDF文件失败")
@@ -63,8 +56,7 @@ func (h *PDFGHandler) DownloadPDF(c *gin.Context) {
if !hit {
h.logger.Warn("PDF文件不存在或已过期",
zap.String("report_id", rawReportID),
zap.String("cache_key", cacheKey),
zap.String("report_id", reportID),
)
h.responseBuilder.NotFound(c, "PDF文件不存在或已过期请重新生成")
return
@@ -74,8 +66,7 @@ func (h *PDFGHandler) DownloadPDF(c *gin.Context) {
expiresAt := createdAt.Add(24 * time.Hour)
if time.Now().After(expiresAt) {
h.logger.Warn("PDF文件已过期",
zap.String("report_id", rawReportID),
zap.String("cache_key", cacheKey),
zap.String("report_id", reportID),
zap.Time("expires_at", expiresAt),
)
h.responseBuilder.NotFound(c, "PDF文件已过期请重新生成")
@@ -84,11 +75,11 @@ func (h *PDFGHandler) DownloadPDF(c *gin.Context) {
// 设置响应头
c.Header("Content-Type", "application/pdf")
// 使用报告ID前缀作为下载文件名的一部分,避免泄露内部缓存键
// 使用报告ID前缀作为下载文件名的一部分
filename := "大数据租赁风险报告.pdf"
if idx := strings.LastIndex(rawReportID, "-"); idx > 0 {
if idx := strings.LastIndex(reportID, "-"); idx > 0 {
// 使用前缀(报告编号部分)作为文件名的一部分
prefix := rawReportID[:idx]
prefix := reportID[:idx]
filename = fmt.Sprintf("大数据租赁风险报告_%s.pdf", prefix)
}
c.Header("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, filename))
@@ -98,8 +89,7 @@ func (h *PDFGHandler) DownloadPDF(c *gin.Context) {
c.Data(http.StatusOK, "application/pdf", pdfBytes)
h.logger.Info("PDF文件下载成功",
zap.String("report_id", rawReportID),
zap.String("cache_key", cacheKey),
zap.String("report_id", reportID),
zap.Int("file_size", len(pdfBytes)),
)
}