英文:
How to access configuration file from subfolder in Go
问题
我得到了一个类似这样的项目结构:
project/
api/
api.go
config/
config.go
config.toml
tests/
api_test.go
main.go
所以,每当我初始化config包时,我尝试使用相对路径config/config.toml
读取配置文件。
当我运行程序go run main.go
时,这个方法运行得很好。
问题出现在我尝试运行测试时:go test project/tests
。我的config包无法找到文件config/config.toml
,因为当前的工作目录不是第一种情况下的project/
,而是project/tests/
。
有没有一种方便的方法可以从run
和test
两种情况下访问配置文件?
英文:
I got a structure of my project that looks pretty like this:
project/
api/
api.go
config/
config.go
config.toml
tests/
api_test.go
main.go
So, whenever I initialize config package I'm trying to read config file using relative path: config/config.toml
.
This works fine as soon as I run my program: go run main.go
The problem appears when I try to run my tests: go test project/tests
. My config package cannot find file config/config.toml
because current work directory is not project/
as in first case but project/tests/
.
Is there any convenient way to access config file from both run
and test
?
答案1
得分: -1
最后,我已经完成了更改配置文件加载行为的工作。之前,加载是在init()
方法中的config
包中完成的。
我创建了一个名为Load(path string)
的方法,根据传递的path
变量加载配置文件。
现在,我在main.go
中这样调用它:
config.Load("config/")
在api_test.go
中这样调用它:
config.Load("../config/")
这不是一个非常整洁的解决方案,但在这种情况下,用户在运行测试时不需要指定任何额外的参数。
英文:
Finally, I've finished with changing the behavior how configuration file is being loaded. Before, the load was done in config
packed inside init()
method.
Instead of this I've created method Load(path string)
that performs load of the configuration file according to path
variable that is passed.
Now, I call it from main.go
like this:
config.Load("config/")
And from api_test.go
like this:
config.Load("../config/")
This is not very neat solution but in that case user is not required to specify any additional parameters while running tests.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论