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.

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

报告相同问题?