在 Linux 环境中对 Golang 项目进行版本控制,需要结合 Go Modules(官方依赖管理)和 Git(代码版本控制)的使用。以下是详细操作指南:
安装 Git
sudo apt-get install git # Debian/Ubuntu
sudo yum install git # CentOS/RHEL
初始化 Git 仓库
cd /path/to/your/project
git init
git add .
git commit -m "Initial commit"
关联远程仓库(如 GitHub/GitLab)
git remote add origin https://github.com/yourname/repo.git
git push -u origin main
初始化 Go Module
在项目根目录执行(Go 1.11+ 支持):
go mod init github.com/yourname/repo # 替换为你的模块路径
go.mod 文件,记录模块信息和依赖版本。添加/更新依赖
import 依赖后,运行以下命令自动下载并记录版本:
bash
go mod tidybash
go get github.com/pkg/errors@v0.9.1依赖版本锁定
go.mod 和 go.sum 文件会精确记录依赖版本,需提交到 Git:
git add go.mod go.sum
git commit -m "Update dependencies"
分支策略
main/master:稳定生产代码develop:开发分支feature/xxxfix/xxx.gitignore 配置
忽略不必要的文件(例如编译产物):
# Go
/bin/
/vendor/
*.exe
*.test
*.prof
# IDE
.vscode/
.idea/
Tag 发布版本
对稳定版本打 Tag(语义化版本 vX.Y.Z):
git tag -a v1.0.0 -m "Release version 1.0.0"
git push origin v1.0.0
如果需要切换不同 Go 版本:
1. 使用 goenv 或 gvm
- 安装 goenv:
bash
git clone https://github.com/syndbg/goenv.git ~/.goenv
echo 'export PATH="$HOME/.goenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(goenv init -)"' >> ~/.bashrc
source ~/.bashrc
- 安装指定 Go 版本:
bash
goenv install 1.20.5
goenv global 1.20.5 # 设置全局版本
bash
go version在 .github/workflows/go.yml 中配置:
name: Go Build
on: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v4
with:
go-version: '1.20'
- run: go mod tidy
- run: go build -v ./...
- run: go test ./...
依赖下载失败
bash
go env -w GOPROXY=https://goproxy.cn,direct版本冲突
go mod why 分析依赖路径:
bash
go mod why github.com/conflicting/pkgbash
go get github.com/pkg@v1.2.3通过以上步骤,你可以在 Linux 环境中高效管理 Golang 项目的版本和依赖。