How can I get a file in a Go web project for testing and production? -


i working on web project use go (with martini) backend. contains reverse-geocoder maps coordinates city names. so, reverse-geocoder has read cities.csv.

the structure is

handlers/city/create.go services/geo/reverse.go services/geo/cities.csv main.go 

now main.go started start web service. handler handlers/city/create.go makes use of services/geo/reverse.go city cities.csv.

the problem cities.csv.

what i've tried

plain filename

however, when use csvfilename := "cities.csv":

  • the tests work
  • the handler doesn't work go assumes /home/me/go/src/github.com/githubuser/backend/cities.csv

adjusted filename

when adjust filename relative root (csvfilename := "services/geocalc/cities.csv"), tests fail. assume /home/me/github/go/src/github.com/githubuser/backend/services/geocalc/services/geocalc/city-names-geocoordinates.csv.

args[0]

this doesn't work either:

filename := filepath.dir(os.args[0]) filedirectory := filepath.dir(filename) csvfilename, _ := filepath.abs(path.join(filedirectory, "cities.csv")) 

now tests fail /tmp/go-build210484207/github.com/githubuser/logbook-backend/services/geocalc/cities.csv

runntime caller

_, filename, _, _ := runtime.caller(1) filedirectory := filepath.dir(filename) csvfilename, _ := filepath.abs(path.join(filedirectory, "cities.csv")) 

works tests, in "production" (testing http-queries) assumes /home/me/github/go/src/github.com/githubuser/backend/handlers/packets/cities.csv

os.getwd()

version 1
filedirectory, _ := os.getwd() csvfilename, _ := filepath.abs(path.join(filedirectory, "cities.csv")) 

fails in production /home/me/github/go/src/github.com/githubuser/logbook-backend/cities.csv.

version 2
filedirectory, _ := os.getwd() csvfilename, _ := filepath.abs(path.join(filedirectory, "services/geo/cities.csv")) 

fails in test /home/me/github/go/src/github.com/githubuser/logbook-backend/services/geo/services/geo/cities.csv

i realized can use gopath environment variable. set (see the gopath environment variable) , 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) 

Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -