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?

  • 写回答

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 深度学习残差模块模型
  • ¥20 两个不同Subnet的点对点连接
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)