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 组策略中的计算机配置策略无法下发
  • ¥15 机器学习简单问题解决
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写