I am currently working on a web project where we use Go (with martini) a backend. It contains a reverse-geocoder which maps coordinates to city names. To do so, the reverse-geocoder has to read a cities.csv
.
The structure is
handlers/city/create.go
services/geo/reverse.go
services/geo/cities.csv
main.go
Now the main.go
is started to start the web service. The handler handlers/city/create.go
makes use of services/geo/reverse.go
to get the city with cities.csv
.
The problem is to get the cities.csv
.
However, when I only use csvFilename := "cities.csv"
:
/home/me/go/src/github.com/githubuser/backend/cities.csv
When I adjust the filename to be relative to the root (csvFilename := "services/geocalc/cities.csv"
), the tests fail. They assume /home/me/GitHub/go/src/github.com/githubuser/backend/services/geocalc/services/geocalc/city-names-geocoordinates.csv
.
This doesn't work either:
filename := filepath.Dir(os.Args[0])
filedirectory := filepath.Dir(filename)
csvFilename, _ := filepath.Abs(path.Join(filedirectory, "cities.csv"))
Now the tests fail with /tmp/go-build210484207/github.com/githubuser/logbook-backend/services/geocalc/cities.csv
_, filename, _, _ := runtime.Caller(1)
filedirectory := filepath.Dir(filename)
csvFilename, _ := filepath.Abs(path.Join(filedirectory, "cities.csv"))
works for the tests, but in "production" (testing with http-queries) it assumes /home/me/GitHub/go/src/github.com/githubuser/backend/handlers/packets/cities.csv
filedirectory, _ := os.Getwd()
csvFilename, _ := filepath.Abs(path.Join(filedirectory, "cities.csv"))
fails in production with /home/me/GitHub/go/src/github.com/githubuser/logbook-backend/cities.csv
.
filedirectory, _ := os.Getwd()
csvFilename, _ := filepath.Abs(path.Join(filedirectory, "services/geo/cities.csv"))
Fails in the test with /home/me/GitHub/go/src/github.com/githubuser/logbook-backend/services/geo/services/geo/cities.csv
I just realized that I can use the GOPATH
environment variable. It is always set (see The GOPATH environment variable) and therefore no additional work:
filedirectory := os.Getenv("GOPATH")
csvFilename, _ := filepath.Abs(path.Join(filedirectory, "src/github.com/gituser/backend/services/geo/cities.csv"))
csvfile, err := os.Open(csvFilename)