CentOS中Golang版本管理方法
GVM是CentOS上最流行的Go多版本管理工具,支持安装、切换、卸载多个Go版本,且能隔离项目环境。
sudo yum install -y git mercurial subversion(确保系统具备编译Go的工具链);gpg --keyserver hkp://pool.sks-keyservers.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB;bash < <(curl -s -S -L https://raw.githubusercontent.com/moovweb/gvm/master/binscripts/gvm-installer);source ~/.gvm/scripts/gvm(使GVM命令生效)。gvm install go1.21.0(支持最新稳定版或历史版本);gvm use go1.21.0 --default(设为默认版本,所有终端生效);gvm list(显示所有已安装的Go版本及当前激活版本);gvm uninstall go1.20.5(删除不需要的版本,释放磁盘空间)。asdf是支持Go、Python、Node.js等多语言的通用版本管理工具,适合需要统一管理多种语言环境的用户。
sudo yum install -y git autoconf automake libtool bison openssl-devel(asdf及Go插件所需工具);git clone https://github.com/asdf-vm/asdf.git ~/.asdf --branch v0.8.1(获取最新稳定版);~/.bashrc或~/.zshrc文件末尾:. $HOME/.asdf/asdf.sh
. $HOME/.asdf/completions/asdf.bash
d. 重新加载配置:source ~/.bashrc(使asdf命令可用)。asdf plugin-add go https://github.com/asdf-vm/asdf-go.git(安装Go语言支持);asdf install go 1.21.0(从官方源下载并编译安装);asdf global go 1.21.0(设为默认版本);asdf list-all go(显示所有可安装的Go版本)。Go Modules是Go 1.11+官方推出的依赖管理工具,虽不直接管理Go运行时版本,但能解决项目级依赖版本问题,配合系统级版本管理工具使用效果更佳。
go mod init github.com/yourname/project(生成go.mod文件,记录项目依赖);go mod tidy(自动下载并添加依赖到go.mod,移除未使用的依赖);go build(根据go.mod中的版本信息编译项目,确保依赖一致性)。go.mod中手动修改依赖版本(如require github.com/gin-gonic/gin v1.9.1);go get -u github.com/gin-gonic/gin(升级到最新版本);go mod tidy(自动移除未使用的依赖项)。g install 1.21安装最新1.21.x版本),适合追求简洁的用户。