How to get the root path of the project

Viewed 14086

I run the following code workingDir, _ := os.Getwd() in server.go file which is under the root project and get the root path, Now I need to move the server.go file to the following structure

myapp
  src
   server.go

and I want to ge the path of go/src/myapp currently after I move the server.go under myapp->src>server.go I got path of go/src/myapp/src/server.go and I want to get the previews path ,

How should I do it in go automatically? or should I put ../ explicit in get path ?

2 Answers

If your project is a git repository you can also use the git rev-parse command with the --show-toplevel:

cmdOut, err := exec.Command("git", "rev-parse", "--show-toplevel").Output()
if err != nil {
    assert.Fail(t, fmt.Sprintf(`Error on getting the go-kit base path: %s - %s`, err.Error(), string(cmdOut)))
    return
}

fmt.Println(strings.TrimSpace(string(cmdOut)))

It'll print out the git project home path wherever in the sub path you are

Related