为什么要得到绝对路径?因为后面上传文件的目录,日志的目录,加载模板文件的目录都需要这个路径。

这里有一点难处理的问题是,需要能同时支持 go run xxx.go 执行,以及相对路径执行./xxxx,和绝对路径执行 /var/www/xxx

go run 执行是为了在开发的时候,能够源码运行,随时调试绝对路径执行 /var/www/xxx,是为了在某些情况下,不能执行切换命令的时候,使用绝对路径去执行文件

这里就不解释获取目录的区别了,直接上代码

 

//判断文件文件夹不存在

func IsFileNotExist(path string) (bool, error) {

_, err := os.Stat(path)

if os.IsNotExist(err) {

return true, nil

}

return false, err

}

//获取程序执行目录

func GetRunPath2() string {

file, _ := exec.LookPath(os.Args[0])

path, _ := filepath.Abs(file)

index := strings.LastIndex(path, string(os.PathSeparator))

ret := path[:index]

return ret

}

//获取程序根目录

func GetRootPath() string {

rootPath, _ := os.Getwd()

if notExist, _ := IsFileNotExist(rootPath); notExist {

rootPath = GetRunPath2()

if notExist, _ := IsFileNotExist(rootPath); notExist {

rootPath = "."

}

}

return rootPath

}

 

这里先用的第一种方式获取,如果没获取到目录,就用第二种方式

后面还遇到了哪些问题和知识点将会继续进行总结。

演示网站:gofly.sopans.com

 

相关文章

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。