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 ?
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/