Pab*_*dez 11 relative-path go revel
我需要引用patients.json从patients.go,这里的文件夹结构:

如果我做:
filepath.Abs("../../conf/patients.json")
它适用go test ./...但却失败了revel run
如果我做:
filepath.Abs("conf/patients.json")
恰恰相反(狂欢很好,但测试失败).
有没有办法正确引用该文件,以便它适用于测试和正常程序运行?
始终将相对路径解释/解析为基本路径:当前或工作目录 - 因此它始终具有其局限性.
如果您可以继续使用正确的工作目录,则可以继续使用相对路径.
我建议不要依赖工作目录,而是明确指定基本路径.这可能在您的应用程序中有一个硬编码的默认值(也可能是工作目录),您应该提供几种方法来覆盖它的值.
推荐的方法来覆盖解析"相对"路径的基本路径:
flag包)os.Getenv())os/user/User和os/user/Current())获得基本路径后,可以通过连接基本路径和相对路径来获取完整路径.您可以使用path.Join()或filepath.Join(),例如:
// Get base path, from any or from the combination of the above mentioned solutions
base := "/var/myapp"
// Relative path, resource to read/write from:
relf := "conf/patients.json"
// Full path that identifies the resource:
full := filepath.Join(base, relf) // full will be "/var/myapp/conf/patients.json"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3048 次 |
| 最近记录: |