How to get the root path of the project
os.Getwd()
does not return your source file path. It returns program current working directory (Usually the directory that you executed your program).
Example:
Assume I have a main.go in /Users/Arman/go/src/github.com/rmaan/project/main.go
that just outputs os.Getwd()
$ cd /Users/Arman/go/src/github.com/rmaan/project/
$ go run main.go
/Users/Arman/go/src/github.com/rmaan/project <nil>
If I change to other directory and execute there, result will change.
$ cd /Users/Arman/
$ go run ./go/src/github.com/rmaan/project/main.go
/Users/Arman <nil>
IMO you should explicitly pass the path you want to your program instead of trying to infer it from context (As it may change specially in production environment). Here is an example with flag
package.
package main
import (
"fmt"
"flag"
)
func main() {
var myPath string
flag.StringVar(&myPath, "my-path", "/", "Provide project path as an absolute path")
flag.Parse()
fmt.Printf("provided path was %s\n", myPath)
}
then execute your program as follows:
$ cd /Users/Arman/go/src/github.com/rmaan/project/
$ go run main.go --my-path /Users/Arman/go/src/github.com/rmaan/project/
provided path was /Users/Arman/go/src/github.com/rmaan/project/
$ # or more easily
$ go run main.go --my-path `pwd`
provided path was /Users/Arman/go/src/github.com/rmaan/project/