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 }