站长博客
站长博客随手笔记
Toggle navigation
站长博客
Home
MacOS
Database
Linux
PHP
Git
Golang
About Me
Archives
Tags
[参考]彻底解决Golang获取当前项目绝对路径问题
2021-07-16 13:31:44
345
0
0
admin
```go package main import ( "fmt" "log" "os" "path" "path/filepath" "runtime" "strings" ) func main() { fmt.Println("getTmpDir(当前系统临时目录) = ", getTmpDir()) fmt.Println("getCurrentAbPathByExecutable(仅支持go build) = ", getCurrentAbPathByExecutable()) fmt.Println("getCurrentAbPathByCaller(仅支持go run) = ", getCurrentAbPathByCaller()) fmt.Println("getCurrentAbPath(最终方案-全兼容) = ", getCurrentAbPath()) } // 最终方案-全兼容 func getCurrentAbPath() string { dir := getCurrentAbPathByExecutable() if strings.Contains(dir,getTmpDir()) { return getCurrentAbPathByCaller() } return dir } // 获取系统临时目录,兼容go run func getTmpDir() string { dir := os.Getenv("TEMP") if dir == "" { dir = os.Getenv("TMP") } res, _ := filepath.EvalSymlinks(dir) return res } // 获取当前执行文件绝对路径 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 } ```
Prev:
Go语言:go-redis客户端之消息的订阅subscribe与发布publish
Next:
消除ADB错误“more than one device and emulator”的方法
0
likes
345
Weibo
Wechat
Tencent Weibo
QQ Zone
RenRen
Table of content