doubeizhong5178 2017-07-21 09:37
浏览 37

如何可靠地使项目扎根?

For now I used runtime.Caller(0) in combination with path.Dir and filepath.Abs to get the path to the currently executed file and get the project root relative to it.

So lets say I've a folder structure like this:

$GOPATH/src/example.org/myproject
$GOPATH/src/example.org/myproject/main.go
$GOPATH/src/example.org/myproject/path
$GOPATH/src/example.org/myproject/path/loader.go

If I want my project root I call the loader.go which in turn gets its path with runtime.Caller(0) and then goes up one folder to reach the project root.

The problem is when using go test -cover the executed file is not in its normal place anymore but in a special sub directory for the testing and coverage analysis.
runtime.Caller(0) gives me the following:

example.org/myproject/path/_test/_obj_/loader.go

Running it through path.Dir and filepath.Abs will give me:

$GOPATH/src/example.org/myproject/path/example.org/myproject/path/_test/_obj_

When I go up from there I won't reach the project root but something totally different obviously. So my questions stands:
Is there any reliable way of getting the project root?

  • 写回答

2条回答 默认 最新

  • doucitan2544 2017-07-21 10:50
    关注

    You can build it from the $GOPATH env variable:

    gp := os.Getenv("GOPATH")
    ap := path.Join(gp, "src/example.org/myproject")
    fmt.Println(ap)
    

    That will yield the absolute path to your paroject dir:

    /path/to/gopath/src/example.org/myproject

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度