How do I get the current GOPATH
from a block of code?
runtime
only has GOROOT
:
// GOROOT returns the root of the Go tree.
// It uses the GOROOT environment variable, if set,
// or else the root used during the Go build.
func GOROOT() string {
s := gogetenv("GOROOT")
if s != "" {
return s
}
return defaultGoroot
}
I could make a function that has GOROOT
replaced with GOPATH
, but is there a buildin for this?
Open settings ( Ctrl+Alt+S ) and navigate to Go | GOPATH. In the file browser, navigate to the directory that you want to associate with GOPATH. In the following example, we configured to use different GOPATH directories for different scopes.
To set GOPATH, open the bashrc/ bash_profle/zshrc file and type the following commands in it and then save the file. pkg − the directory that will contain the packages and shared object files if any. src − the directory where all the code you will write will be stored.
To check if the GOPATH has been appropriately configured open run dialog by pressing win + r and type %GOPATH% and hit the OK button. If it takes you to the C:\Projects\Go directory, the configuration was successful.
The GOPATH environment variable lists places to look for Go code. On Unix, the value is a colon-separated string. On Windows, the value is a semicolon-separated string. On Plan 9, the value is a list.
Use os.Getenv
From docs:
Getenv retrieves the value of the environment variable named by the key. It returns the value, which will be empty if the variable is not present.
Example:
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println(os.Getenv("GOPATH"))
}
Update for Go 1.8+
Go 1.8 has default GOPATH exported via go/build:
package main
import (
"fmt"
"go/build"
"os"
)
func main() {
gopath := os.Getenv("GOPATH")
if gopath == "" {
gopath = build.Default.GOPATH
}
fmt.Println(gopath)
}
You should use go/build package.
package main
import (
"fmt"
"go/build"
)
func main() {
fmt.Println(build.Default.GOPATH)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With