下面给你一份CentOS 下 Golang 配置的最佳实践(以 CentOS 7 / 8 / Stream 为例,覆盖安装、环境、目录结构、代理、构建与运维)。
不要用 yum install golang(版本太旧)
# 以 1.22 为例
cd /usr/local/src
wget https://go.dev/dl/go1.22.5.linux-amd64.tar.gz
rm -rf /usr/local/go
tar -C /usr/local -xzf go1.22.5.linux-amd64.tar.gz
vim /etc/profile.d/go.sh
export GOROOT=/usr/local/go
export GOPATH=/opt/gopath
export PATH=$GOROOT/bin:$GOPATH/bin:$PATH
# 代理(国内必配)
export GOPROXY=https://goproxy.cn,direct
export GOSUMDB=sum.golang.org
# 开启模块
export GO111MODULE=on
source /etc/profile
go version
/opt/gopath
├── bin
├── pkg
└── src
/opt/apps/your-project
├── cmd/
│ └── server/
│ └── main.go
├── internal/
├── pkg/
├── config/
├── go.mod
├── go.sum
└── Makefile
go mod init github.com/yourname/project
go mod tidy
⚠️ 注意:
vendor/(除非离线部署)go.sum 必须提交go env -w GOPROXY=https://goproxy.cn,direct
go env -w GOSUMDB=off # 如公司内网
查看:
go env
CGO_ENABLED=0 GOOS=linux go build -o server cmd/server/main.go
./server
vim /etc/systemd/system/your-app.service
[Unit]
Description=Go App
After=network.target
[Service]
User=app
WorkingDirectory=/opt/apps/your-project
ExecStart=/opt/apps/your-project/server
Restart=always
[Install]
WantedBy=multi-user.target
systemctl daemon-reload
systemctl enable your-app
systemctl start your-app
pprof + PrometheusGOMAXPROCSexport GOMAXPROCS=4
go vet / golangci-lintgo mod init demo
go build -o app main.go
./app
如果你愿意,我可以:
你现在是 学习 / 生产 / 容器 哪种场景?