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.
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).