Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

加餐版--实用的文件和目录操作 #84

Open
kevinyan815 opened this issue Sep 7, 2022 · 0 comments
Open

加餐版--实用的文件和目录操作 #84

kevinyan815 opened this issue Sep 7, 2022 · 0 comments

Comments

@kevinyan815
Copy link
Owner

kevinyan815 commented Sep 7, 2022

上个目录里,汇总的都是文件读写、压缩相关的操作。在做项目时还会有其他必要的使实用操作,就总结到这里。

获取当前执行函数的文件路径

此操作在加载配置文件之类的程序里会用到。
程序需要根据自己当前的路径,确定配置文件在哪里,这样无论Go项目程序放在什么路编译,都能正确加载到配置文件。

//获取当前文件路径
_, filename, _, _ := runtime.Caller(0)

确定项目根目录的路径

通过上一步获取当前执行函数的文件路径后,还能更进一步通过 path.Dir 获取项目根目录,或者配置文件目录的路径。

这里假设当前文件的上两层目录,就是项目根目录,这时候这么获取项目根目录路径。

//获取当前文件路径
_, filename, _, _ := runtime.Caller(0)
// 项目根目录
rootPath := path.Dir(path.Dir(path.Dir(filename)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant