1、下载源码,从 Go 的官方存储库下载指定版本的源码包
[root@centos7 opt]# wget https://go.dev/dl/go1.23.4.src.tar.gz
2、解压源码包到 /usr/local 目录
[root@centos7 opt]# tar xf go1.23.4.src.tar.gz -C /usr/local/
3、编译go
[root@centos7 opt]# cd /usr/local/go/src/
[root@centos7 src]# ./make.bash
ERROR: Cannot find /root/go1.4/bin/go.
Set $GOROOT_BOOTSTRAP to a working Go tree >= Go 1.20.6.
报错,不要慌,这是因为 go 的编译需要一个已有的 go 运行环境作为引导工具链。这是 go 编译的一个基本需求。
以下是详细的解决方法:
- 下载 1.20.6 预编译的 go 二进制包
[root@centos7 opt]# wget https://go.dev/dl/go1.20.6.linux-amd64.tar.gz
- 解压
[root@centos7 opt]# tar xf go1.20.6.linux-amd64.tar.gz
[root@centos7 opt]# mv go /usr/local/go-1.20.6
- 将 GOROOT_BOOTSTRAP 设置为刚解压的 Go 1.20.6 目录
[root@centos7 opt]# echo "export GOROOT_BOOTSTRAP=/usr/local/go-1.20.6" >> /etc/profile
[root@centos7 opt]# source /etc/profile
- 为确保持久生效,可将其添加到
~/.bashrc
:
[root@centos7 opt]# echo 'export GOROOT_BOOTSTRAP=/usr/local/go-1.20.6' >> ~/.bashrc
[root@centos7 opt]# source ~/.bashrc
4、继续编译go
[root@centos7 opt]# cd /usr/local/go/src/
[root@centos7 src]# ./make.bash
Building Go cmd/dist using /usr/local/go-1.20.6. (go1.20.6 linux/amd64)
Building Go toolchain1 using /usr/local/go-1.20.6.
Building Go bootstrap cmd/go (go_bootstrap) using Go toolchain1.
Building Go toolchain2 using go_bootstrap and Go toolchain1.
Building Go toolchain3 using go_bootstrap and Go toolchain2.
Building packages and commands for linux/amd64.
---
Installed Go for linux/amd64 in /usr/local/go
Installed commands in /usr/local/go/bin
*** You need to add /usr/local/go/bin to your PATH.
[root@centos7 src]# /usr/local/go/bin/go version
go version go1.23.4 linux/amd64
5、设置go环境变量
[root@centos7 ~]# echo 'export PATH=$PATH:/usr/local/go/bin' >> ~/.bashrc
[root@centos7 ~]# source ~/.bashrc
[root@centos7 ~]# go version
go version go1.23.4 linux/amd64
6、验证环境配置
[root@centos7 ~]# go env
GO111MODULE=''
GOARCH='amd64'
GOBIN=''
GOCACHE='/root/.cache/go-build'
GOENV='/root/.config/go/env'
......//省略部分内容
7、清理引导工具链
[root@centos7 ~]# rm -rf /usr/local/go-1.20.6/
#删除/etc/profile文件里面的以下内容
export GOROOT_BOOTSTRAP=/usr/local/go-1.20.6