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


本文摘自网络,作者runningstarh,侵删。

func checkErr(err error) {
	if err != nil {
		panic(err)
	}
}

//获取当前的执行路径
//C:\Users\Vic\AppData\Local\Tempfunc getCurrentPath() string {
	s, err := exec.LookPath(os.Args[0])
	checkErr(err)
	i := strings.LastIndex(s, "\\")
	path := string(s[0 : i+1])
	return path
}

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


func main()  {
	//D:\Go\workspace\port
	pa,_:=os.Getwd()
	path:=getCurrentPath()
	filePath:=CurrentFile()
	fmt.Println(pa)
	fmt.Println(path)
	fmt.Println(filePath)
}

一、为什么写这样的一篇文章,因为我在获取当前文件的详细路径时找不到对应的方法,我将详细展示三种的源码方案


相关阅读 >>

Go语言中Goroot、Gopath、Gobin详解

Golang不适合开发web吗

Golang位运算符

Go语言队列的链式表示和实现

聊聊Gorm的groupby

Golang 快速排序与 php 快速排序

聊聊Go-ddd-sample

Golang有web框架吗

Golang cap是什么意思

手撸Golang 仿spring ioc/aop 之5 如何扫描

更多相关阅读请进入《Go》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...