dqlm80253 2015-03-28 20:13
浏览 45
已采纳

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

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.

What I've tried

plain filename

However, when I only use csvFilename := "cities.csv":

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

adjusted filename

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.

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 the tests fail with /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 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

os.Getwd()

Version 1
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.

Version 2
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

  • 写回答

1条回答 默认 最新

  • dounai1986 2015-03-29 16:54
    关注

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 outlook无法配置成功
  • ¥15 Pwm双极模式H桥驱动控制电机
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换