golang获取三种不同路径的方法(执行路径、项目路径、文件路径)

984 阅读1分钟
//获取当前的执行路径
func getCurrentPath() string {
   s, err := exec.LookPath(os.Args[0])
   if err != nil {
      panic(err)
   }
   i := strings.LastIndex(s, "\\")
   path := string(s[0 : i+1])
   return path
}

//获取当前文件的详细路径
func CurrentFile() string {
   _, file, _, ok := runtime.Caller(1)
   if !ok {
      panic(errors.New("Can not get current file info"))
   }
   return file
}

func main() {
   //当前项目的路径
   pa, _ := os.Getwd()
   
   path := getCurrentPath()
   
   filePath := CurrentFile()
   
   fmt.Println("项目路径:", pa)
   fmt.Println("当前的执行路径:", path)
   fmt.Println("当前文件的详细路径:", filePath)
}

// Output:
// 项目路径: D:\goproject\src\Data_Struct
// 当前的执行路径: C:\Users\li184\AppData\Local\Temp\GoLand\  
// 当前文件的详细路径: D:/goproject/src/Data_Struct/li/main.go

需要解释的一点是:当前文件的执行路径就是go build之后生成的exe可执行文件存储的位置