Home > Enterprise >  os.Getenv("GOPATH") not retrieving value in Ubuntu
os.Getenv("GOPATH") not retrieving value in Ubuntu

Time:04-12

I am noob in Golang, also I have browsed all the answers relative to this issue in stackoverflow but I haven't found anthing to answer my problem.

If I enter the command in console -> get env I got this:

GO111MODULE=""
GOARCH="amd64"
GOBIN=""
GOCACHE="/home/adi/.cache/go-build"
GOENV="/home/adi/.config/go/env"
GOEXE=""
GOEXPERIMENT=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOINSECURE=""
GOMODCACHE="/home/adi/go/pkg/mod"
GONOPROXY=""
GONOSUMDB=""
GOOS="linux"
GOPATH="/home/adi/go"
GOPRIVATE=""
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/snap/go/9415"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/snap/go/9415/pkg/tool/linux_amd64"
GOVCS=""
GOVERSION="go1.18"
GCCGO="gccgo"
GOAMD64="v1"
AR="ar"
CC="gcc"
CXX="g  "
CGO_ENABLED="1"
GOMOD="/dev/null"
GOWORK=""
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build1114163046=/tmp/go-build -gno-record-gcc-switches"

but if I am trying to output

func main() {
    // router := gin.Default()
    // RegisterBlocklyAutomationEndpoint(router)

    fmt.Println(os.Getenv("GOPATH"))

}

I get an empty string. I really need to get the value in order to use it in path formation for some static resources.

Thanks!

CodePudding user response:

Your problem is that go env is not a reliable indicator of whether or not $GOPATH is set.

If you type go env | grep GOPATH and then env | grep GOPATH, I am willing to bet that you see something like this:

$ go env |grep GOPATH
GOPATH="/home/user/go"
$ env |grep GOPATH
$

What is happening is that go env is giving you the default value, but it's not actually set.

If you need to get the current working directory, then os.Getwd() is probably a better choice.

CodePudding user response:

There are better answers but consider this:

The env var GOPATH may exists buy it should be exported to be visible in a subshell

  • Related