我目前正在开发一个Web项目,我们使用Go(带马提尼)后端。它包含一个反向地理编码器,可将坐标映射到城市名称。为此,反向地理编码器必须阅读cities.csv
。
结构是
handlers/city/create.go
services/geo/reverse.go
services/geo/cities.csv
main.go
现在main.go
开始启动Web服务。处理程序handlers/city/create.go
使用services/geo/reverse.go
来获取
有cities.csv
的城市。
问题是获得cities.csv
。
但是,当我只使用csvFilename := "cities.csv"
时:
/home/me/go/src/github.com/githubuser/backend/cities.csv
当我将文件名调整为相对于根(csvFilename := "services/geocalc/cities.csv"
)时,测试失败。他们假设/home/me/GitHub/go/src/github.com/githubuser/backend/services/geocalc/services/geocalc/city-names-geocoordinates.csv
。
这也不起作用:
filename := filepath.Dir(os.Args[0])
filedirectory := filepath.Dir(filename)
csvFilename, _ := filepath.Abs(path.Join(filedirectory, "cities.csv"))
现在测试失败了/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"))
适用于测试,但在“生产”(使用http查询进行测试)中,它假定为/home/me/GitHub/go/src/github.com/githubuser/backend/handlers/packets/cities.csv
filedirectory, _ := os.Getwd()
csvFilename, _ := filepath.Abs(path.Join(filedirectory, "cities.csv"))
使用/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"))
使用/home/me/GitHub/go/src/github.com/githubuser/logbook-backend/services/geo/services/geo/cities.csv
答案 0 :(得分:0)
我刚刚意识到我可以使用GOPATH
环境变量。它总是被设置(见The GOPATH environment variable),因此没有额外的工作:
filedirectory := os.Getenv("GOPATH")
csvFilename, _ := filepath.Abs(path.Join(filedirectory, "src/github.com/gituser/backend/services/geo/cities.csv"))
csvfile, err := os.Open(csvFilename)