feat: 增加判断是否 go run 运行

This commit is contained in:
2026-01-03 22:27:06 +08:00
parent ee7a78ab6c
commit 1f6145405e

View File

@@ -36,6 +36,10 @@ func (p *project) GetFileSystemSeparator() string {
// BuildPath 构建路径
func (p *project) BuildPath(filePathList ...string) string {
projectRootPath, _ := p.GetExecutablePath()
if p.IsRunningWithGoRun() {
// go run 运行, 则工作目录为项目目录
projectRootPath = p.GetWorkDir()
}
if len(filePathList) == 0 {
// 降为获取项目根目录
return projectRootPath
@@ -68,3 +72,29 @@ func (p *project) GetHomeDir() string {
homePath, _ := homedir.Dir()
return homePath
}
// IsRunningWithGoRun 获取程序是否通过 go run 运行
func (p *project) IsRunningWithGoRun() bool {
// 方法1: 检查执行文件路径是否包含临时目录特征
exePath, err := os.Executable()
if err != nil {
return false
}
// go run 会在临时目录创建二进制文件
// 不同系统的临时目录特征:
switch runtime.GOOS {
case "windows":
// Windows: 通常在 C:\Users\<user>\AppData\Local\Temp\go-build\
return strings.Contains(exePath, "go-build") ||
strings.Contains(exePath, `\go-build\`) ||
strings.Contains(filepath.Base(exePath), "go-build")
case "darwin", "linux":
// macOS/Linux: 通常在 /tmp/go-build/
return strings.Contains(exePath, "/go-build/") ||
strings.Contains(exePath, "/go-build") ||
(strings.HasPrefix(exePath, "/var/folders/") && strings.Contains(exePath, "/go-build/"))
}
return false
}