温馨提示×

Golang CentOS如何设置

小樊
32
2026-08-03 09:10:29
栏目: 编程语言

下面分几种常见场景,说明 在 CentOS 上设置 / 使用 Golang(Go 语言) 的方法。你可以按需要选择。


一、在 CentOS 上安装 Golang

✅ 方法一:官方二进制包(推荐,版本新、稳定)

1. 卸载旧版本(如果有)

sudo rm -rf /usr/local/go

2. 下载 Go(以 1.22 为例)

cd /tmp
wget https://go.dev/dl/go1.22.4.linux-amd64.tar.gz

如果没装 wget

sudo yum install -y wget

3. 解压到 /usr/local

sudo tar -C /usr/local -xzf go1.22.4.linux-amd64.tar.gz

4. 配置环境变量

编辑 ~/.bashrc~/.bash_profile

export PATH=$PATH:/usr/local/go/bin
export GOPATH=$HOME/go
export PATH=$PATH:$GOPATH/bin

生效:

source ~/.bashrc

5. 验证

go version

输出类似:

go version go1.22.4 linux/amd64

✅ 方法二:使用 yum / dnf(版本较旧)

CentOS 7

sudo yum install -y golang

CentOS 8 / Stream

sudo dnf install -y golang

查看版本:

go version

⚠️ 仓库中的 Go 版本通常较老,不推荐生产环境使用。


二、配置 Go 环境变量(重要)

常用环境变量说明

变量 说明
GOROOT Go 安装目录(一般不用设置)
GOPATH Go 工作目录(默认 ~/go
GO111MODULE 是否启用 Go Modules
GOPROXY 模块代理(国内推荐)

推荐配置(国内环境)

export GO111MODULE=on
export GOPROXY=https://goproxy.cn,https://goproxy.io,direct

写入 ~/.bashrc

echo 'export GO111MODULE=on' >> ~/.bashrc
echo 'export GOPROXY=https://goproxy.cn,https://goproxy.io,direct' >> ~/.bashrc
source ~/.bashrc

三、测试 Go 是否正常工作

1. 创建测试项目

mkdir -p ~/hello
cd ~/hello
go mod init hello

2. 编写代码

package main

import "fmt"

func main() {
    fmt.Println("Hello, CentOS Go!")
}

3. 运行

go run main.go

四、CentOS 防火墙 & 网络(Go 服务常见)

开放端口(如 8080)

sudo firewall-cmd --permanent --add-port=8080/tcp
sudo firewall-cmd --reload

五、常见问题

1. go: command not found

  • 环境变量没生效
  • 检查 /usr/local/go/bin 是否在 PATH

2. 下载慢

  • 使用国内代理:
go env -w GOPROXY=https://goproxy.cn,direct

3. CentOS 7 太老

  • 建议使用 CentOS 7 + 官方 Go
  • 或升级到 CentOS Stream / Rocky / AlmaLinux

六、总结(最简步骤)

wget https://go.dev/dl/go1.22.4.linux-amd64.tar.gz
sudo tar -C /usr/local -xzf go1.22.4.linux-amd64.tar.gz
echo 'export PATH=$PATH:/usr/local/go/bin' >> ~/.bashrc
source ~/.bashrc
go version

如果你有更具体的需求(比如 CentOS 7 / 8、Docker、Go Web 服务、systemd 自启、交叉编译),可以直接告诉我,我可以一步步给你配置。

0