Files
tyapi-server/internal/shared/pdf/resources_path.go
2025-12-04 13:20:03 +08:00

107 lines
3.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package pdf
import (
"os"
"path/filepath"
"go.uber.org/zap"
)
var globalLogger *zap.Logger
// SetGlobalLogger 设置全局logger用于资源路径查找
func SetGlobalLogger(logger *zap.Logger) {
globalLogger = logger
}
// GetResourcesPDFDir 获取resources/pdf目录路径
// resources目录和可执行文件同级例如
// /app/tyapi-server (可执行文件)
// /app/resources/pdf (资源文件)
func GetResourcesPDFDir() string {
// 从可执行文件所在目录查找resources和可执行文件同级
if execPath, err := os.Executable(); err == nil {
execDir := filepath.Dir(execPath)
// 处理符号链接
if realPath, err := filepath.EvalSymlinks(execPath); err == nil {
execDir = filepath.Dir(realPath)
}
// resources目录和可执行文件同级
resourcesPath := filepath.Join(execDir, "resources", "pdf")
absPath, err := filepath.Abs(resourcesPath)
if err == nil {
if globalLogger != nil {
globalLogger.Debug("尝试从可执行文件目录查找资源",
zap.String("exec_path", execPath),
zap.String("exec_dir", execDir),
zap.String("resources_path", absPath),
)
}
if _, err := os.Stat(absPath); err == nil {
if globalLogger != nil {
globalLogger.Info("找到resources/pdf目录", zap.String("path", absPath))
}
return absPath
} else if globalLogger != nil {
globalLogger.Debug("资源目录不存在", zap.String("path", absPath), zap.Error(err))
}
}
}
// 后备方案:从工作目录查找(开发环境)
if workDir, err := os.Getwd(); err == nil {
resourcesPath := filepath.Join(workDir, "resources", "pdf")
absPath, err := filepath.Abs(resourcesPath)
if err == nil {
if globalLogger != nil {
globalLogger.Debug("尝试从工作目录查找资源",
zap.String("work_dir", workDir),
zap.String("resources_path", absPath),
)
}
if _, err := os.Stat(absPath); err == nil {
if globalLogger != nil {
globalLogger.Info("找到resources/pdf目录", zap.String("path", absPath))
}
return absPath
}
}
// 开发环境可能在工作目录的子目录
resourcesPath = filepath.Join(workDir, "tyapi-server-gin", "resources", "pdf")
absPath, err = filepath.Abs(resourcesPath)
if err == nil {
if globalLogger != nil {
globalLogger.Debug("尝试从工作目录子目录查找资源",
zap.String("resources_path", absPath),
)
}
if _, err := os.Stat(absPath); err == nil {
if globalLogger != nil {
globalLogger.Info("找到resources/pdf目录", zap.String("path", absPath))
}
return absPath
}
}
}
// 最后的后备:返回绝对路径(即使目录不存在)
if workDir, err := os.Getwd(); err == nil {
resourcesPath := filepath.Join(workDir, "resources", "pdf")
if absPath, err := filepath.Abs(resourcesPath); err == nil {
if globalLogger != nil {
globalLogger.Warn("未找到resources/pdf目录返回后备路径", zap.String("path", absPath))
}
return absPath
}
}
// 最后的最后:返回相对路径(不推荐)
if globalLogger != nil {
globalLogger.Error("无法确定resources/pdf目录路径")
}
return filepath.Join("resources", "pdf")
}