Coder Perfect

On Ubuntu, how can I set the GOPATH environment variable? What file do I need to change?

Problem

I’m attempting a go get:

go get github.com/go-sql-driver/mysql

It also fails with the following message:

package github.com/go-sql-driver/mysql: cannot download, $GOPATH not set. For more details see: go help gopath

When I run go env, I get the following list of Go values:

ubuntu@ip-xxx-x-xx-x:~$ go env
GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH=""
GORACE=""
GOROOT="/usr/lib/go"
GOTOOLDIR="/usr/lib/go/pkg/tool/linux_amd64"
CC="gcc"
GOGCCFLAGS="-g -O2 -fPIC -m64 -pthread"
CGO_ENABLED="1"

clearly the GOPATH is not set, how and where do I set it?

There are a lot of postings about this problem, but none that answer my question of which file has to be updated to provide a value for this location.

Asked by David Saintloth

Solution #1

New Way:

Take a look at this response.

Old Way:

Simply add the following lines to /.bashrc to keep this going. However, instead of $HOME/go in my example, you can use whatever path you like as GOPATH.

export GOPATH=$HOME/go
export PATH=$PATH:$GOROOT/bin:$GOPATH/bin

Answered by Daniel Lin

Solution #2

Since Go 1.11, you no longer need to utilize GOPATH. Simply browse to your project directory and do the following steps:

go mod init github.com/youruser/yourrepo

If you insist on using GOPATH, take note of the following:

From the documentation:

Answered by Inanc Gumus

Solution #3

Ubuntu 14.04

export GOPATH=$HOME/go

You may also save this string to a file.

$HOME/.bashrc

Answered by pasha.zhukov

Solution #4

The GOPATH variable should point to a freshly built empty directory. This is the “workspace” for Go, where it downloads packages and other things. /.go is what I use.

For example:

mkdir ~/.go
echo "GOPATH=$HOME/.go" >> ~/.bashrc
echo "export GOPATH" >> ~/.bashrc
echo "PATH=\$PATH:\$GOPATH/bin # Add GOPATH/bin to PATH for scripting" >> ~/.bashrc
source ~/.bashrc

source: http://www.larry-price.com/blog/2013/12/15/setting-up-a-go-environment-in-ubuntu-12-dot-04/

Answered by Bryan Larsen

Solution #5

If it’s an Ubuntu, for example, after installing the packages:

$sudo apt install golang -y

Simply add the following lines to your /.bashrc file (Of your user)

export GOROOT=/usr/lib/go
export GOPATH=$HOME/go
export PATH=$PATH:$GOROOT/bin:$GOPATH/bin

Answered by firebitsbr

Post is based on https://stackoverflow.com/questions/21001387/how-do-i-set-the-gopath-environment-variable-on-ubuntu-what-file-must-i-edit