This guide will show you how to install multiple versions of go and have the version switch automatically when you change directory.
The two main tools used are asdf which is a general tool version manager with support for multiple languages (like nvm, pyenv, rbenv) and programming tools. And direnv which is a tool to load environment variables depending on the current directory.
Note: for the brew install and asdf install steps you may need to disconnect from the VPN.
brew install direnvAdd the following line at the end of the ~/.zshrc file:
echo -e '\neval "$(direnv hook zsh)"' >> ${ZDOTDIR:-~}/.zshrcAdd the following line at the end of the ~/.config/fish/config.fish file:
echo -e "direnv hook fish | source" >> ~/.config/fish/config.fishbrew install asdfAdd asdf.sh to your ~/.zshrc with:
echo -e "\n. $(brew --prefix asdf)/libexec/asdf.sh" >> ${ZDOTDIR:-~}/.zshrcAdd asdf.fish to your ~/.config/fish/config.fish with:
echo -e "\nsource "(brew --prefix asdf)"/libexec/asdf.fish" >> ~/.config/fish/config.fishInstall the golang and direnv plugins
asdf plugin-add golangasdf plugin-add direnv
# substitute zsh for bash, fish etc
asdf direnv setup --shell zsh --version systemFirst remove your existing go installation and unset GOROOT from your profile. If you have installed via homebrew:
brew uninstall goThen install and configure a global go version
asdf install golang 1.18
asdf global golang 1.18This populates a global ~/.tool-versions file with the configured tool version.
Verify with go version
Then navigate to a repo and set a local go version
asdf install golang 1.16
asdf local golang 1.16This populates a local .tool-versions file with the local golang version.
To have your local go variables set automatically add the following to an .envrc file in the repo folder. You can also
set other repo-specific environment variables here to load automatically e.g. CGO_ENABLED or GO_FLAGS
# .envrc in project root folder
CGO_ENABLED=0 # add other project variables you need
use asdf # adds shims for tools defined in .tool-versionsAnytime you change the .envrc file, direnv will warn you that it's changed and prompt you to review and approve before automatically loading the variables. This is to prevent automatically loading unexpected changes. If you edit the file with direnv edit your changes will be approved automatically.
You may also need to configure a global ~/.envrc with
use asdf
export GOROOT="$(asdf where golang)/go"
Finally, the .tool-versions and .envrc files should be added to your global ~/.gitignore to avoid conflicting with
other developers.
To configure GoLand you can set the GOROOT in the preferences to
~/.asdf/installs/golang/VERSION/go
TODO find a way to automate this.
https://youtrack.jetbrains.com/issue/GO-9008/Support-local-Go-installations-with-asdf
