如何在Go中从子文件夹访问配置文件

huangapple go评论76阅读模式
英文:

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/

有没有一种方便的方法可以从runtest两种情况下访问配置文件?

英文:

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.

huangapple
  • 本文由 发表于 2015年9月2日 22:02:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/32355314.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定