duandianwen1723
2015-09-02 14:02
浏览 32
已采纳

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

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?

图片转代码服务由CSDN问答提供 功能建议

我的项目结构看起来像这样:

   project / 
 api / 
 api.go 
 config / 
 config.go 
 config.toml 
测试/ 
 api_test.go 
 main.go 
   
 
 

因此,每当我初始化配置程序包时,我都会尝试使用相对路径: config / config.toml 读取配置文件。 这在我运行时就可以正常工作 我的程序: go run main.go

当我尝试运行测试时出现问题: go test project / tests 。 我的配置包找不到文件 config / config.toml ,因为当前工作目录不是第一种情况的 project / ,而是 project / tests /

是否可以通过 run test 访问配置文件?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dozr162106 2015-09-02 14:40
    已采纳

    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.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题