如何在Go Web项目中获取文件以进行测试和生产?

时间:2015-03-28 20:13:39

标签: go

我目前正在开发一个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

ARGS [0]

这也不起作用:

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

runntime caller

_, 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

os.Getwd()

版本1
filedirectory, _ := os.Getwd()
csvFilename, _ := filepath.Abs(path.Join(filedirectory, "cities.csv"))

使用/home/me/GitHub/go/src/github.com/githubuser/logbook-backend/cities.csv生产失败。

版本2
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

进行测试失败

1 个答案:

答案 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)