脚本宝典收集整理的这篇文章主要介绍了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 }
以上是脚本宝典为你收集整理的Go 获取当前项目路径 支持go run go build 两种方式全部内容,希望文章能够帮你解决Go 获取当前项目路径 支持go run go build 两种方式所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。