返回
Golang相对路径与绝对路径不一致
2023-09-22 1841 0
你遇到过 go run main.go 或go build main.go 获取到的路径不一样的问题吗?
Go程序的两种执行方式
第一种使用go run xx.go,常用于本地开发
第二种使用go build xx.go 常用于生产环境,通过此命令构建成二进制文件然后上传到服务器再执行
两种方式下带来的问题
使用go run 命令执行
func getCurrentAbPathByExecutable() string {
exePath, err := os.Executable()
if err != nil {
fmt.Print(err)
}
res, _ := filepath.EvalSymlinks(filepath.Dir(exePath))
return res
}
func main() {
curPath := getCurrentAbPathByExecutable()
fmt.Println(curPath)
}
// go run main.go 输出
// tmp/go-build4104269073/b001/exe
使用go build 命令执行
func getCurrentAbPathByExecutable() string {
exePath, err := os.Executable()
if err != nil {
fmt.Print(err)
}
res, _ := filepath.EvalSymlinks(filepath.Dir(exePath))
return res
}
func main() {
curPath := getCurrentAbPathByExecutable()
fmt.Println(curPath)
}
// go build main.go 输出
// /opt/go_code/demo/path
可以看出,这两种不同的方式生成的路径 是不同的
产生不同路径的原因
这是由于go run会将源代码编译到系统TEMP或TMP环境变量目录中并启动执行;而go build只会在当前目录编译出可执行文件,并不会自动执行。
解决办法
使用 runtime.caller(0)来解决
func getCurrentAbPathByExecutable() string {
var absPath string
_, file, _, ok := runtime.Caller(0)
if ok {
absPath = path.Dir(file)
}
return absPath
}
func main() {
curPath := getCurrentAbPathByExecutable()
fmt.Println(curPath)
}
这样写的话,无论执行go run xx.go 或者 go build xx.go 返回的路径 都是一样的
网友点评
提交
相关阅读
TinyMCE上传图片文件路径变为相对路径的解决方法
MySQL当前读、快照读和幻读的关系
.NET8和.NET6的区别有哪些?
Gemma 4 开源发布:Google 再掀轻量级大模型革命,AI 普惠时代加速到来
全球最大暗网论坛 XSS.is 核心管理员在乌克兰落网
javascript字母散落特效
出海电商网站必备:如何选择高效可靠的云服务器
progress设置颜色
相关帖子
GBA模拟器最新版 VisualBoyAdvance-M v2.2.2 可玩GBA GB GBC游戏附游戏ROM
安卓、PC单机游戏:GTA三部曲合集 GTA罪恶都市/GTA圣安地列斯/侠盗猎车手3
阿里云99元的云服务器真的好用吗?
Switch游戏资源下载 Switch烧录卡资源 Mig-Switch游戏合集 烧录卡 1.75T
魔兽世界时光服 | 80级暗影牧师(暗牧)PVE输出天赋加点、雕文推荐与输出手法全攻略
尔湾云(ErWan Cloud)机场加速器评测|加速性能、稳定性与价格全面解析
微软魔兽世界和网易复合 还需要骨灰盒恢复账号角色吗?
流量光机场全面评测 | 2025年最新用户体验分析,值得入手吗?