Go 获取当前项目路径 支持go run go build 两种方式

Go 获取当前项目路径,通过 os.Executable() go run 和go build是不同的路径。

提供通用的解决方法如下:

 

复制代码
package main

import (
    "fmt"
    "log"
    "os"
    "path"
    "path/filepath"
    "runtime"
    "strings"
)

func main() {
    fmt.Println("getTmpDir(当前系统临时目录) = ", os.TempDir())
    fmt.Println("getCurrentAbPathByExecutable(仅支持go build) = ", getCurrentAbPathByExecutable())
    fmt.Println("getCurrentAbPathByCaller(仅支持go run) = ", getCurrentAbPathByCaller())
    fmt.Println("getCurrentAbPath(最终方案-全兼容) = ", getCurrentAbPath())
}

// 最终方案-全兼容
func getCurrentAbPath() string {
    dir := getCurrentAbPathByExecutable()
    tmpDir, _ := filepath.EvalSymlinks(os.TempDir())
    if strings.Contains(dir, tmpDir) {
        return getCurrentAbPathByCaller()
    }
    return dir
}

// 获取当前执行文件绝对路径
func getCurrentAbPathByExecutable() string {
    exePath, err := os.Executable()
    if err != nil {
        log.Fatal(err)
    }
    res, _ := filepath.EvalSymlinks(filepath.Dir(exePath))
    return res
}

// 获取当前执行文件绝对路径(go run)
func getCurrentAbPathByCaller() string {
    var abPath string
    _, filename, _, ok := runtime.Caller(0)
    if ok {
        abPath = path.Dir(filename)
    }
    return abPath
}
复制代码

 

posted on   星河赵  阅读(1367)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
历史上的今天:
2017-03-22 jquery 给每个li增加事件

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示