[英]How to reliably get the projects root in go?
現在我將runtime.Caller(0)
與path.Dir
和filepath.Abs
結合使用來獲取當前執行文件的路徑並獲取相對於它的項目根目錄。
所以假設我有一個這樣的文件夾結構:
$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
如果我想要我的項目根目錄,我調用 loader.go ,它反過來使用runtime.Caller(0)
獲取它的路徑,然后上升一個文件夾到達項目根目錄。
問題是當使用go test -cover
,執行的文件不再位於其正常位置,而是位於用於測試和覆蓋率分析的特殊子目錄中。
runtime.Caller(0)
給了我以下內容:
example.org/myproject/path/_test/_obj_/loader.go
通過path.Dir
和filepath.Abs
運行它會給我:
$GOPATH/src/example.org/myproject/path/example.org/myproject/path/_test/_obj_
當我從那里上去時,我不會到達項目根目錄,但顯然完全不同。 所以我的問題是:
有沒有可靠的方法來獲取項目根?
您可以從$GOPATH
變量構建它:
gp := os.Getenv("GOPATH")
ap := path.Join(gp, "src/example.org/myproject")
fmt.Println(ap)
這將產生你的 paroject 目錄的絕對路徑:
/path/to/gopath/src/example.org/myproject
這顯然只在設置了GOPATH
時才有效。 又名。 在你的開發機器上。 在生產中,您需要通過配置文件提供目錄。
看到這個答案。 如果您使用的是 go ~ 1.8, func Executable() (string, error)
是我在需要時偶然發現的一個選項。 我簡要測試了它如何與go test -cover
交互,它似乎工作正常:
func Executable() (string, error)
Executable 返回啟動當前進程的可執行文件的路徑名。 不能保證路徑仍然指向正確的可執行文件。 如果使用符號鏈接啟動進程,則取決於操作系統,結果可能是符號鏈接或其指向的路徑。 如果需要穩定的結果, path/filepath.EvalSymlinks 可能會有所幫助。
package main
import (
"fmt"
"os"
"path"
)
func main() {
e, err := os.Executable()
if err != nil {
panic(err)
}
path := path.Dir(e)
fmt.Println(path)
}
測試:
binpath.go
:
package binpath
import (
"os"
"path"
)
func getBinPath() string {
e, err := os.Executable()
if err != nil {
panic(err)
}
path := path.Dir(e)
return path
}
binpath_test.go
:
package binpath
import (
"fmt"
"testing"
)
func TestGetBinPath(t *testing.T) {
fmt.Println(getBinPath())
}
結果類似於/tmp/go-build465775039/github.com/tworabbits/binpath/_test
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.