download2565
2018-04-04 15:00 阅读 40
已采纳

Go项目的结构

My program uses several files like *.json, *.db

How should i place they? First variant:

project
    |-> src
        |-> main
            | main.go
            | main_test.go
            |-> data
                | database.db
        |-> config
            | config.go
            |-> data
                | config.json
        ...

Or:

project
    |-> src
        |-> main
            | main.go
            | main_test.go
        |-> config
            | config.go
        ...
    |-> data
        | database.db
        | config.json

I would prefer second variant, but I get troubles when try to write tests. I tried to use "/absolute/path", but it doesn't work, because it points to ".../src/main/ folder.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dongtan3395 dongtan3395 2018-04-04 15:05

    The go test command sets the working directory to the directory containing the package source files. For example, the config tests are run with the working directory set to project/src/config:

    Use paths relative to that directory from tests:

    A test in the first variant should open files like this:

     f, err := os.Open("data/config.json")
     if err != nil {
         // handle error
     }
    

    A test in the second variant should should open files like this:

     f, err := os.Open("../../data/config.json")
     if err != nil {
         // handle error
     }
    

    (the important point here is the relative path, not that os.Open is used).

    点赞 评论 复制链接分享

相关推荐