Go CI/CD:GitHub Actions 与 GitLab CI 全流程实战
高效 CI/CD 是研发心脏。本文以两个主流平台为案例,从语言环境到多阶段流水线讲透。
一、GitHub Actions 基础
.github/workflows/go.yml:
name:Goon:[push,pull_request]jobs:test:runs-on:ubuntu-lateststeps:-uses:actions/checkout@v4-uses:actions/setup-go@v5with:go-version:1.22-run:go mod download-run:go test ./...-race-coverprofile=coverage.out-run:go vet ./...-run:|curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh ./bin/golangci-lint run-uses:codecov/codecov-action@v3二、build 缓存加速
-uses:actions/setup-go@v5with:go-version:1.22cache:trueactions/setup-go 自动缓存 go module,但只缓存GOPATH/pkg/mod。要缓存 build cache 用 Go 1.18+ 的GOCACHE路径。
-uses:actions/cache@v3with:path:|~/.cache/go-build ~/go/pkg/modkey:${{runner.os}}-go-${{hashFiles('**/go.sum')}}restore-keys:|${{ runner.os }}-go-三、GitLab CI 模板
.gitlab-ci.yml:
stages:-lint-test-build-deploylint:image:golang:1.22stage:lintbefore_script:-go mod downloadscript:-go vet ./...test:image:golang:1.22stage:testbefore_script:-go mod downloadscript:-go test ./...-race-coverprofile=cov.outartifacts:reports:coverage_report:coverage_format:coberturapath:cov.out四、多平台镜像构建
build:runs-on:ubuntu-lateststeps:-uses:docker/setup-buildx-action@v3-uses:docker/login-action@v3with:registry:ghcr.iousername:${{github.actor}}password:${{secrets.GITHUB_TOKEN}}-uses:docker/build-push-action@v5with:push:truetags:|ghcr.io/${{ github.repository }}:${{ github.sha }} ghcr.io/${{ github.repository }}:latestcache-from:type=ghacache-to:type=gha,mode=max五、镜像签名 + SBOM
-uses:sigstore/cosign-installer@v3-run:|cosign sign ghcr.io/${{ github.repository }}:latest-uses:anchore/sbom-action@v0with:image:ghcr.io/${{github.repository}}:latestSBOM 满足企业合规需求。
六、自动发布到 K8s
deploy:runs-on:ubuntu-lateststeps:-uses:actions/checkout@v4-uses:azure/setup-kubectl@v3-run:|echo "${{ secrets.KUBECONFIG }}" | base64 -d > /tmp/kubeconfig KUBECONFIG=/tmp/kubeconfig kubectl set image deploy/user-svc user-svc=ghcr.io/org/user-svc:${{ github.sha }} -n user七、矩阵测试
test:strategy:matrix:go:[1.21,1.22,1.23]runs-on:ubuntu-lateststeps:-uses:actions/checkout@v4-uses:actions/setup-go@v5with:go-version:${{matrix.go}}-run:go test ./...多版本并行跑测试。
八、踩坑清单
- Self-hosted runner:避免泄露 secrets
runs-onGPU 限制:macOS runner 略慢- actions/cache 大小限制:5GB 单条
- 容器内子模块:用
actions/checkout@v4+ submodules: ‘recursive’
九、生产实战:多环境部署
jobs:build:# ...dev-deploy:needs:buildif:github.ref == 'refs/heads/main'environment:devsteps:-run:deploy-dev.shprod-deploy:needs:buildif:startsWith(github.ref,'refs/tags/v')environment:prodsteps:-run:deploy-prod.sh按 tag / branch 触发不同环境。
十、GitHub Environments + Approvals
Settings → Environments → Required reviewers,双人复核方能部署。
十一、总结与展望
CI/CD 三件套:
- 编译 / 测试 / 静态扫描
- 镜像构建 / 多平台分发
- 自动部署 / 一键回滚
未来:AI 加持的 CI(如自动测试生成、smart flow)、Pipeline 标准化模板化将更深入。
十二、参考文献
- GitHub Actions 官方文档
- GitLab CI 文档
- kubernetes-deploy-action 仓库