Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current GOPATH from code

Tags:

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?

like image 510
RickyA Avatar asked Sep 18 '15 10:09

RickyA


People also ask

How do I find my Gopath?

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.

How do I find Gopath in Linux?

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.

How do I find Gopath in Windows?

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.

What should be the Gopath value?

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.


2 Answers

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)
}
like image 76
codefreak Avatar answered Oct 05 '22 09:10

codefreak


You should use go/build package.

package main

import (
    "fmt"
    "go/build"
)

func main() {
    fmt.Println(build.Default.GOPATH)
}
like image 27
rhysd Avatar answered Oct 05 '22 10:10

rhysd