下面给你一份在 CentOS 上配置 Golang 开发环境 的常用、稳妥做法(以 CentOS 7 / 8 为例,也适用于 Rocky / Alma)。
这是最干净、可控的方式。
cd /usr/local/src
wget https://go.dev/dl/go1.22.5.linux-amd64.tar.gz
版本号可自行替换(https://go.dev/dl/)
tar -C /usr/local -xzf go1.22.5.linux-amd64.tar.gz
~/.bashrc 或 /etc/profilevi ~/.bashrc
添加:
export GOROOT=/usr/local/go
export GOPATH=$HOME/go
export PATH=$PATH:$GOROOT/bin:$GOPATH/bin
source ~/.bashrc
go version
# CentOS 7
yum install golang -y
# CentOS 8 / Rocky
dnf install golang -y
⚠️ 版本通常较老,不建议生产或新项目使用。
go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.cn,direct
go env
mkdir ~/hello && cd ~/hello
go mod init hello
hello.go
package main
import "fmt"
func main() {
fmt.Println("Hello, CentOS + Golang!")
}
运行:
go run hello.go
go install golang.org/x/tools/gopls@latest
go install github.com/go-delve/delve/cmd/dlv@latest
# 开放端口
firewall-cmd --permanent --add-port=8080/tcp
firewall-cmd --reload
✅ command not found: go
→ 检查 PATH 是否包含 /usr/local/go/bin
✅ go: cannot find main module
→ 在项目中执行 go mod init xxx
✅ 下载依赖慢
→ 确认 GOPROXY 已配置
如果你告诉我:
我可以直接给你一套更针对性的配置方案。