Golang equivalent of npm install -g

Update: If you're using Go 1.16, this answer still works, but go install has changed and is now the recommended method for installing executable packages. See Karim's answer for an explanation: https://stackoverflow.com/a/68559728/10490740

Using Go >= 1.11, if your current directory is within a module-based project, or you've set GO111MODULE=on in your environment, go get will not install packages "globally". It will add them to your project's go.mod file instead.

As of Go 1.11.1, setting GO111MODULE=off works to circumvent this behavior:

GO111MODULE=off go get github.com/usr/repo

Basically, by disabling the module feature for this single command, it will install to GOPATH as expected.

Projects not using modules can still go get normally to install binaries to $GOPATH/bin.

There's a lengthy conversation and multiple issues logged about this change in behavior branching from here: golang/go - cmd/go: go get should not add a dependency to go.mod #27643.


Starting with Go >= 1.16 the recommended way to install an executable is to use

go install package@version

For example, go install github.com/fatih/gomodifytags@latest.

Executables (main packages) are installed to the directory named by the GOBIN environment variable, which defaults to $GOPATH/bin or $HOME/go/bin if the GOPATH environment variable is not set. You need to add this directory to your PATH variable to run executables globally. In my case, I've added this line to my ~/.zshrc file. (if you are using bash, add it to the ~/.bash_profile file):

export PATH="$HOME/go/bin:$PATH"

Go team published a blog post about this change, here's the explanation quote:

We used to recommend go get -u program to install an executable, but this use caused too much confusion with the meaning of go get for adding or changing module version requirements in go.mod.

Refer to go install documentation for more details